如何为多对多关系设置强参数

How to set strong parameter for many to many relationship

我有一个模型 Word,它通过结点 table word_to_words 具有多对多关系 TranslationTranslationWord class 本身。

这些是它的源代码。

app/models/word.rb

class Word < ApplicationRecord
  has_many :word_to_words
  has_many :translations, through: :word_to_words
end

app/models/word_to_word.rb

class WordToWord < ApplicationRecord
  belongs_to :word
  belongs_to :translation, class_name: 'Word'
end

app/views/words/_form.html.erb

<%= form_for(word) do |f| %>
  <%= f.text_field :name %>
  <%= f.fields_for :translations, word.translations.build do |q| -%>
    <%= q.text_field :name %>
  <% end -%>
  <%= f.submit %>
<% end %>

app/controllers/words_controller.rb

def word_params
  params.require(:word).permit(:name, :pronunciation,
                               word_to_words_attributes: [:word_id, :translation_id],
                               translations_attributes: [:id, :name]
  )
end

当我创建一个新词时,translation 变量被拒绝并出现错误 Unpermitted parameter

Parameters: {"utf8"=>"✓", "authenticity_token"=>"xxx", "word"=>{"name"=>"foo", "translations"=>{"name"=>"bar"}}, "commit"=>"Create Word"}
Unpermitted parameter: translations

我认为这是因为我的强参数配置有误。 strong参数应该怎么设置?

你应该使用 nested_attributes.

class Word < ApplicationRecord
  has_many :word_to_words
  has_many :translations, through: :word_to_words
  accepts_nested_attributes_for :translations
end

迁移可以是:

class CreateWordToWords < ActiveRecord::Migration[5.0]
  def change
    create_table :word_to_words do |t|
      t.belongs_to :word, index: true, foreign_key: true
      t.belongs_to :translation, index: true, foreign_key: true

      t.timestamps
    end
  end
end