【发布时间】:2015-12-12 07:52:55
【问题描述】:
我有 4 个关系复杂的模型。其中 3 个应该有描述,应该只对创建的用户启用。换句话说,每个用户都有自己对 Group(例如)或 Post 或其他内容的描述。让我们只讨论一个模型,因为其他模型非常相似。我拥有的: user.rb
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :omniauthable, omniauth_providers: [:vkontakte]
has_and_belongs_to_many :groups
has_many :descriptions
end
group.rb
class Group < ActiveRecord::Base
has_and_belongs_to_many :users
has_many :descriptions, :as => :describable
accepts_nested_attributes_for :descriptions
end
description.rb
class Description < ActiveRecord::Base
belongs_to :user
belongs_to :describable, :polymorphic => true
end
描述表
create_table "descriptions", force: :cascade do |t|
t.integer "user_id" -- belongs_to
t.string "content"
t.integer "describable_id"
t.string "describable_type"
end
如何显示属于 current_user 的组的描述(我使用设计)?如何构建具有嵌套描述的更新表单?
我尝试这样做,但它不起作用。我已经就部分问题提出了问题here。
【问题讨论】:
-
您在 User 模型中缺少多态关联的一部分,它应该是
has_many :descriptions, as: :describable(您在 Group 模型中正确地拥有它) -
@Roma149 用户不是可描述的模型。它只是有很多关于 has_many - belongs_to 的描述。并且这个描述描述了模型组、帖子等。
-
好的,但是
Description模型中没有belongs_to :user,所以我想如果您尝试使用该关联会出错。 -
@Roma149 谢谢,已修复
标签: ruby-on-rails devise relationship nested-forms nested-attributes