The following relationship models are available:
class question has_many —answares accepts_nested_attributes_for —answares end class Answer belongs_to:question end
Under these assumptions, within the controller,
@question.answares.attributes
When I try to do so,
NoMethodError: undefined method `attributes' for #Answere::ActiveRecord_Associations_CollectionProxy
The error appears.
※ ApplicationController is inherited.If you add a symbol, it doesn't display well, so it's omitted. class QuestionsController @question.answares.attributes=answere_params private defanswere_params xxxxxxxx end end
In a one-to-one relationship, you can use the attributes method, but in a one-to-many relationship like this, how is it common to implement it?
The implementation of answer_params has been verified during debugging, and there is no problem with its operation.
It contains the expected value, but I would like to eventually cram it into answer and save it.
If there are any deficiencies, I will supplement them.
Thank you for your cooperation.
ruby-on-rails ruby
@question.answers
will be a collection of answers
, so if you want to get answers
, you can call it as follows:
@question.answers.first.attributes
Also, there are several ways to add a new answer
to @questions
, but why not use build
?
@[email protected](answer_params)
[email protected]
…
else
…
end
Note: Rails Guide 4.3.1.14 collection.build(attributes={},...)
© 2024 OneMinuteCode. All rights reserved.