在導軌3我有2個模型:用戶,事件。用戶has_many事件通過events_staffs和事件has_many事件通過events_staffs。導軌3協會沒有表
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]
是可能做到的呢?
SOLUTION
#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
是的,它給予你描述的作家,成員等的關係 –