嵌套属性,将current_user.id传递给嵌套模型

时间:2013-06-20 12:51:29

标签: ruby-on-rails ruby-on-rails-3 nested-attributes

我有3个型号:用户,答案和问题。

user.rb

 has_many :questions
 has_many :answers

question.rb

 has_many :answers
 belongs_to :user
 accept_nested_attributes_for :answers

answer.rb

 belongs_to :question
 belongs_to :user

在questions / show.html.erb

 form_for @question do |f|
   f.fields_for :answers, @question.answers.build do |builder|
     builder.text_area, :body
   end

   f.submit
 end

提交调用问题#update action,并且由于嵌套资源,新答案将保存在数据库中。我想知道:在提交问题后,如何在数据库中保存user_id列的答案?提交表单后,我可以以某种方式将current_user.id传递回答user_id列吗?

3 个答案:

答案 0 :(得分:4)

您必须在控制器的创建操作中传递user参数(您还应该在控制器中构建嵌套属性):

def new
  @question = Question.new
  @question.answers.build
end

def create
  @question = current_user.questions.new(params[:questions])
  //The line below is what will save the current user to the answers table 
  @question.answers.first.user = current_user

  ....
end 

因此,您的视图形式应如下所示:

form_for @question do |f|
   f.fields_for :answers do |builder|
     builder.text_area, :body
 end

 f.submit

答案 1 :(得分:1)

您可以在控制器的更新操作中执行以下操作:

# questions_controller
def update
   params[:question][:answers_attributes].each do |answer_attribute|
     answer_attribute.merge!(:user_id => current_user.id)
   end

  if @question.update_attributes(params[:question])
    ...
  end
end

另一个更简单的解决方案是将user_id添加到表单中,如下所示:

form_for @question do |f|
  f.fields_for :answers, @question.answers.build(:user_id => current_user.id) do |builder|
    builder.text_area, :body
    builder.hidden_field :user_id # This will hold the the user id of the current_user if the question is new
  end

  f.submit
end

此方法的问题在于用户可以通过HTML源代码检查器(如chrome中)编辑值,从而将用户设置为其他人。你当然可以用某种方式验证这一点,但这也有点复杂。

答案 2 :(得分:-2)

'current_user'是一个设计辅助方法。它可以直接在控制器和视图中访问。 如果我没有错,只有新的答案应该有current_user.id旧​​的答案不应该更新。你可以这样做

f.fields_for :answers, @question.answers.build do |a|
  a.hidden_field :user_id, :value => current_user.id
  a.submit