三个模型之间的关联
association between three models
在这个我正在努力做的工作协会中度过美好的一天,使用 nested_form
#_form.html.erb in post
<%= f.fields_for :addresses do |address| %>
<% address.association :state %>
<% end %>
class Post < ApplicationRecord
has_many :addresses, as: :addressable, dependent: :destroy
accepts_nested_attributes_for :addresses, allow_destroy: true
end
class Address < ApplicationRecord
belongs_to :states
belongs_to :addressable, :polymorphic => true
end
class State < ApplicationRecord
has_many :addresses
end
打印错误:关联:未找到状态!!!
帮帮我!
更改您的 State
class 代码。
class Address < ApplicationRecord
belongs_to :state
belongs_to :addressable, :polymorphic => true
end
您使用了 states
而不是 state
。因此,您遇到了错误。
来自docs:
class Book < ApplicationRecord
belongs_to :author
end
belongs_to associations must use the singular term. If you used the
pluralized form in the above example for the author association in the
Book model, you would be told that there was an "uninitialized
constant Book::Authors". This is because Rails automatically infers
the class name from the association name. If the association name is
wrongly pluralized, then the inferred class will be wrongly pluralized
too.
所以你必须替换行:
belongs_to :states
和
belongs_to :state
在这个我正在努力做的工作协会中度过美好的一天,使用 nested_form
#_form.html.erb in post
<%= f.fields_for :addresses do |address| %>
<% address.association :state %>
<% end %>
class Post < ApplicationRecord
has_many :addresses, as: :addressable, dependent: :destroy
accepts_nested_attributes_for :addresses, allow_destroy: true
end
class Address < ApplicationRecord
belongs_to :states
belongs_to :addressable, :polymorphic => true
end
class State < ApplicationRecord
has_many :addresses
end
打印错误:关联:未找到状态!!! 帮帮我!
更改您的 State
class 代码。
class Address < ApplicationRecord
belongs_to :state
belongs_to :addressable, :polymorphic => true
end
您使用了 states
而不是 state
。因此,您遇到了错误。
来自docs:
class Book < ApplicationRecord belongs_to :author end
belongs_to associations must use the singular term. If you used the pluralized form in the above example for the author association in the Book model, you would be told that there was an "uninitialized constant Book::Authors". This is because Rails automatically infers the class name from the association name. If the association name is wrongly pluralized, then the inferred class will be wrongly pluralized too.
所以你必须替换行:
belongs_to :states
和
belongs_to :state