I have 3 models: User, Answer and Question.
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
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 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?
'current_user' is a devise helper method. it can be accessed in controllers n views directly. if i m not wrong, only the new answer should have the current_user.id Old answers should not be updated. u can do this as
You could do something like this in your controller's update action:
Another more simple solution would be to add the user_id to your form like this:
The problem with this approach is that users would be able to edit the value through a HTML source code inspector (like in chrome), and thereby set the user to someone else. You could of course validate this in some way, but that too would be a bit complex.
You have to pass the user parameter in your controller's create action (also you should build your nested attributes in the controller):
Your view's form should therefore look like:
end