【问题标题】:rails 3 association without table没有表格的rails 3关联
【发布时间】:2014-01-08 11:08:23
【问题描述】:

在 Rails 3 中,我有 2 个模型:用户、事件。用户 has_many 事件通过 events_staffs 和 Event has_many 事件通过 events_staffs。

class Staff < ActiveRecord::Base
  has_many :events_staffs
  has_many :events, through: :events_staffs
end

class Event < ActiveRecord::Base
  has_many :events_staffs, dependent: :destroy
  has_many :staffs, through: :events_staffs
end

我希望一个活动有一个作者和一些成员,其中作者和成员是员工表的记录。 我希望我可以在控制台中做这样的事情:

e=Event.first #ok it works
e.author=Staff.first
e.members=Staff.all - [Staff.first]

有可能吗?

解决方案

#Event model
  has_many :events_staffs, dependent: :destroy
  has_many :members, through: :events_staffs, source: :staff   #http://stackoverflow.com/a/4632456/1066183

  #http://stackoverflow.com/a/13611537/1066183
  belongs_to :author,class_name: 'Staff'


#migration:
class AddForeignKeyToEventsTable < ActiveRecord::Migration
  def change
    change_table :events do |t|
      t.integer :author_id
    end
  end
end

【问题讨论】:

  • 是的,前提是您已经描述了作者、成员等关系。

标签: ruby-on-rails activerecord console has-many-through


【解决方案1】:

是的,很简单。将 author_id 整数列添加到您的 Event 模型中,然后按如下方式更新您的代码:

class Event < ActiveRecord::Base
  has_many :events_staffs, dependent: :destroy
  has_many :staffs, through: :events_staffs

  belongs_to :author, class_name: 'Staff'
end

至于成员,我会创建另一个类似于您的 staffs_events 表的连接表,但针对成员。在该模型中,您需要执行与 Event 相同的 belongs_to 关联,您可以在其中为成员指定 class_name。

【讨论】:

  • 好的,谢谢。是否可以使用您的解决方案但无需编辑数据库?
  • 否 - 您需要一个新列来跟踪您所指的作者的 ID。
猜你喜欢
  • 2022-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-15
  • 2011-07-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多