Purpose of model variable in respond_with

余生长醉 提交于 2019-12-12 02:39:10

问题


In Rails 3, using the new respond_to and respond_with constructs, I do this:

class SurveysController < ApplicationController
  respond_to :html

  def survey
    @program_id = params[:program_id]
    @participant_id = params[:participant_id]
    respond_with [@program_id, @participant_id]
  end
end

When the view is displayed (survey.html.erb) the variables program_id, @participant_id are both properly set up. However, if I omit them from the respond_with, as follows:

class SurveysController < ApplicationController
  respond_to :html

  def survey
    @program_id = params[:program_id]
    @participant_id = params[:participant_id]
    @foo = "foo"
    respond_with @foo
  end
end

The same two instance variables are still visible in the view. In other words, all instance variables from the action are made available from within the view.

Question: why should I put instance variables on the respond_to line?


回答1:


You are correct that any instance variable you set in the action method will be accessible in the corresponding view. In your case, you are just setting id's to the instance variables, not an actual resource (i.e. @survey = Survey.find_by_program_id(params[:program_id]))

respond_with will send a response with the appropriate format for the resource that you give it...so you wouldn't use respond_with for all of your instance variables, you would use it for the resource. If you added an additional format like :json, then if the request was for survey.json, the respond_with would convert your @survey resource into the appropriate json format.

respond_to :html, :json
def survey
  @program_id = params[:program_id]
  @participant_id = params[:participant_id]
  @survey = Survey.find_by_program_id(params[:program_id])
  respond_with @survey
end

Not sure if that makes total sense to you, but this article might be helpful.



来源:https://stackoverflow.com/questions/13276046/purpose-of-model-variable-in-respond-with

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!