[英]Pass new object id within create controller ruby on rails
I'm hoping this is easy.... =) 我希望这很容易.... =)
I've got a question object, and a favanswer object, question has_one favanswer, favanswer belongs_to question. 我有一个问题对象,一个favanswer对象,一个问题has_one favanswer,一个favanswer includes_to问题。 I've got a favanswer_id column and index in my question model, I'm trying to pass the newly posted favanswer_id to the corresponding question objects' favanswer_id field.
我的问题模型中有一个favanswer_id列和索引,我正在尝试将新发布的favanswer_id传递到相应问题对象的favanswer_id字段。 Maybe it's a lot more..or less..complicated than this,.but in the favanswer_controller I have the below in the create action, and I'm just trying to figure out how to correct line 6, or whatever I need to do, because without 6 it works fine, it just doesn't update my question model...Help?
也许比这复杂得多..或更少..但是在favanswer_controller中,我在create动作中包含以下内容,而我只是想弄清楚如何纠正第6行,或者我需要做的事情,因为没有6,它可以正常工作,只是不更新我的问题模型...帮助吗?
1 def create
2
3 @answer = Answer.find(params[:answer_id])
4 @question = @answer.question_id
5 Favanswer.create(favanswer_params.merge(user: current_user, question_id: @question))
6 Question.update(@question, :favanswer_id => "HOW DO I PASS THE NEW FAVANSWER ID HERE?")
7 redirect_to question_path(@question)
8
9 end
I think the mistake you're making here is referring to the foreign key of the association directly. 我认为您在这里犯的错误是直接引用关联的外键。 Instead, rely on the association as an object.
而是将关联作为对象。 When you create the
Favanswer
, pass in the @answer.question
object and not the id. 创建
Favanswer
,请传递@answer.question
对象,而不要传递ID。 Additionally, don't pass it in to question_id
but rather to question
另外,不要将其传递给
question_id
,而是要question
def create
@answer = Answer.find(params[:answer_id])
@question = @answer.question
Favanswer.create(favanswer_params.merge(user: current_user, question: @question))
redirect_to question_path(@question)
end
Rails is friendly and kind and when you assign the Question instance to the named association, it will hook it up as required, so you have no need to update the Question directly. Rails友好友好,当您将Question实例分配给命名的关联时,它将根据需要进行连接,因此您无需直接更新Question。
Model.create
returns an instance of the newly created Model, which is useful for what you're trying to do. Model.create
返回新创建的Model的实例,这对于您尝试执行的操作很有用。 That means: 这意味着:
@favanswer = Favanswer.create(favanswer_params.merge(user: current_user, question_id: @question))
Question.update(@question, :favanswer_id => @favanswer.id)
Will accomplish what you're after. 会成就您的追求。
smh... 嗯...
figured it out =) 想通了=)
@L = Favanswer.create(favanswer_params.merge(user: current_user, question_id: @question))
Question.update(@question, :favanswer_id => @L.id)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.