Best way to build a JSON API coupled with HTML views in a Rails project

I’ve got a Rails eCommerce project communicating with an iOS app. The iOS app receives JSON data from the Rails back-end, but there’s also HTML rendering when a user comes to the project from his browser. They basically call the same actions (create, destroy, update, etc.) from both sides.

/website/my_action → HTML rendering
/website/my_action.json → API

What’s the best way to organize our Rails app to stay DRY and avoid messy code / code smell ? The project currently uses respond_to a lot but i’m wondering if we shouldn’t switch to a split system with default json response:


And if so, how would you do concretely?

Here’s a sample of one method in the current system

  def get_following

    @user = User.find(params[:id]) 

    respond_to do |format|
      format.html { render :index }
      format.json { render :json => ApiFormat.success(:followers, user.following) }


It looks fine but becomes very messy in some methods I prefer not to show. In short: how would you refacto the project in a more efficient way?


To me it seems like it would make more sense to split them with an api namespace for all the json controllers. What did you end up doing?


Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *