【问题标题】:How to add a new attribute to Associate Table column in rails如何向 Rails 中的关联表列添加新属性
【发布时间】:2012-12-05 06:28:51
【问题描述】:

在我的 rails 应用程序中,我必须为关联表添加一个名为 is_leader 的新列。

关联表的关系如下:

has_and_belongs_to_many :analysis_responses, :join_table => "analysis_responses_participants"

以下是将参与者详细信息保存到数据库的代码:

organization.people.create(participant)

participant 具有以下值

name: Test User
position: 
birthdate: 
id: 
lead: "1"

如果前导值为 1,则特定记录的 is_leader 列值应为 1

我想知道如何在 rails 的关联表中保存 is_leader

谢谢

【问题讨论】:

  • 不回答你的问题,但是:在 Rails 中最好的做法是让布尔属性 notis_ 为前缀。其他语言中的这种做法部分是由于方法名称中缺乏? 支持。因为 Rails 为布尔属性创建了 ? 方法,所以最好将列命名为 leader 并使用 leader? 检查其值是否为真
  • @Deefour:非常感谢您的建议。我会改的

标签: mysql ruby-on-rails ruby ruby-on-rails-3.1 associations


【解决方案1】:

如果您需要在连接表上保存属性,那么您将不得不使用连接模型而不是 HABTM。

class Organization
  has_many :analysis_responses
  has_many :people, through: :analysis_responses
end

class AnalysisResponse
  belongs_to :organization
  belongs_to :person
end

class Person
  has_many :analysis_responses
  has_many :organizations, through: :analysis_reponses
end

【讨论】:

  • 好的,在这种情况下,如何将领导者属性保存在关联表中?
  • 在我的 analysis_response 类中,我添加了以下内容:has_and_belongs_to_many :participants, :class_name => "Person", :join_table => "analysis_responses_participants"
  • 您无法将信息保存到has_an_belongs_to_many 中的连接表中。您必须使用连接模型。
  • 非常感谢肖恩。这很有帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-28
相关资源
最近更新 更多