【问题标题】:Private fields for multiple models, how to make on RoR?多个模型的私有字段,如何在 RoR 上制作?
【发布时间】: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


【解决方案1】:

为什么你有一个名为description 的额外模型?

虽然它本身不是问题,但你真的不需要有一个模型只是为了描述。

--

个人资料

相反,您可能希望将详细信息放入 profile 模型中,或者只是放入 user 模型中(adding extra attributes to a Devise model 没有任何问题)。

我们使用 profile 模型,它使我们能够向user 模型添加任意数量的“额外”字段:

你可以这样设置:

#app/models/user.rb
class User < ActiveRecord::Base
   has_one :profile
   accepts_nested_attributes_for :profile
   before_create :build_profile

   delegate :description, :name, to: :profile, prefix: false #-> @user.description
end

#app/models/profile.rb
class Profile < ActiveRecord::Base
   belongs_to :user
end

这将允许您为每个用户创建一个配置文件,在创建用户时构建该配置文件,然后根据需要更改配置文件中的任意多个选项。

【讨论】:

  • @Rich_Peck 我的英语不太好,抱歉。我已经用更多解释更新了我的问题。因此,任何用户都可以对组、板、帖子等进行描述。这将类似于用于记录任何类型的私人笔记。我需要它只对其创建者/所有者可见。如果我正确理解你,你会回答我如何向用户对象添加描述。
  • 是的,我回答了我认为您要问的问题。如果用户可以为组/板等创建描述,那么这将是一个完全不同的答案。我会在一分钟内更新
猜你喜欢
  • 1970-01-01
  • 2013-10-18
  • 1970-01-01
  • 2010-10-09
  • 1970-01-01
  • 2015-06-09
  • 1970-01-01
  • 1970-01-01
  • 2020-03-23
相关资源
最近更新 更多