Наконец-то все заработало:
posts_controller.rb
@post = @character.posts.create(post_params)
...
def post_params
params.require(:post).permit( conversation_attributes: [ missives_attributes: [ :content ] ] )
end
post.rb
has_one :conversation, class_name: 'Postconversation', dependent: :destroy, inverse_of: :post
accepts_nested_attributes_for :conversation
postconversation.rb
belongs_to :post, inverse_of: :conversation
has_many :missives, class_name: 'Postmissive', dependent: :destroy, foreign_key: 'conversation_id', inverse_of: :conversation
accepts_nested_attributes_for :missives
postmissive.rb
belongs_to :conversation, class_name: 'Postconversation', foreign_key: 'conversation_id', inverse_of: :missives
validates :conversation, presence: true # validates :conversation_id does not work
_post_form.html.erb
<%= f.fields_for :conversation_attributes do |ff| %>
<%= ff.fields_for 'missives_attributes[]', Postmissive.new do |fff| %>
<%= hidden_field_tag :callsign, character.callsign %>
<%= fff.text_area :content %>
...
<% end %>
<% end %>
Представленные параметры
Parameters: {"utf8"=>"✓", "authenticity_token"=>"mxHD...VoA==", "callsign"=>"baz", "post"=>{"conversation_attributes"=>{"missives_attributes"=>[{"content"=>"Hello"}]}}}
Примечания
1) Обратите внимание на добавление inverse_of:
, так что Rails распознаетдвунаправленная ассоциация.Сохранение базы данных не удается без этого.В документах говорится, что необходимо использовать только с has_one
и has_many
, но в некоторых ответах на Stack Overflow говорится, что его также следует использовать с belongs_to
, поэтому я так и сделал (belongs_to :post, inverse_of: :conversation
и belongs_to :conversation, inverse_of: :missives
),Дальнейшее понимание этого приветствия.
2) post_params
в порядке, как есть.Нет необходимости добавлять какие-либо скобки.
3) В postmissive.rb
проверка должна была быть validates :conversation
, а не validates :conversation_id
.
4) Стефан Вир был прав,missives_attributes
должен быть представлен как массив.Спасибо Kartikey Tanna за этот ответ о том, как этого добиться.