嵌套属性,将current_user.id传递给嵌套模型 [英] nested attributes, passing current_user.id to nested model

查看:46
本文介绍了嵌套属性,将current_user.id传递给嵌套模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3个模型:用户,答案和问题.

I have 3 models: User, Answer and Question.

user.rb

 has_many :questions
 has_many :answers

question.rb

question.rb

 has_many :answers
 belongs_to :user
 accept_nested_attributes_for :answers

answer.rb

answer.rb

 belongs_to :question
 belongs_to :user

在questions/show.html.erb中

In 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

Submit调用questions#update操作,由于嵌套了资源,新答案将被保存在数据库中.我想知道:提交问题后,如何在数据库中保存user_id列的答案?提交表单后,我可以通过某种方式将current_user.id传递给答案的user_id列吗?

Submit calls the questions#update action and, thanks to nested resources, will the new answer be saved in the database. I wonder: how can I save the user_id column for answer, in the database, after the question is submitted? Can I somehow pass current_user.id to answer's user_id column after submitting the form?

推荐答案

您必须在控制器的create操作中传递用户参数(也应在控制器中构建嵌套属性):

You have to pass the user parameter in your controller's create action (also you should build your nested attributes in the controller):

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 

您的视图的表格因此应如下所示:

Your view's form should therefore look like:

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

 f.submit

结束

这篇关于嵌套属性,将current_user.id传递给嵌套模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆