首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >三种模型间的关联

问三种模型间的关联
EN

Stack Overflow用户
提问于 2016-08-06 14:44:39
回答 2查看 65关注 0票数 0

在我尝试做的工作中,使用nested_form,祝您愉快

代码语言:javascript
复制
#_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

打印错误:关联:状态未找到!帮帮我!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-08-06 15:23:12

来自文档

类书< ApplicationRecord belongs_to :author belongs_to关联必须使用单数术语。如果您在上述示例中为Book模型中的author关联使用了复数形式,您将被告知存在一个“未初始化的常量Book::Authors”。这是因为Rails从关联名称中自动推断类名。如果关联名是错误的多元化,那么推断类也会被错误地多元化。

所以你必须替换这条线:

代码语言:javascript
复制
belongs_to :states

使用

代码语言:javascript
复制
belongs_to :state
票数 0
EN

Stack Overflow用户

发布于 2016-08-06 15:00:35

更改State类代码。

代码语言:javascript
复制
class Address < ApplicationRecord
  belongs_to :state
  belongs_to :addressable, :polymorphic => true
end

您使用的是states而不是state。因此,您将得到错误。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38805491

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档