Question

in rails 3 i have 2 models: User,Event. User has_many Event through events_staffs and Event has_many Event through 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

i wish that an Event have an author and some members where author and members are record of staffs table. I wish I could do in the console something like this:

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

is possible to do it?

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
Was it helpful?

Solution

Yes, quite easy. Add an author_id integer column to your Event model, then update your code as follows:

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

  belongs_to :author, class_name: 'Staff'
end

As for members, I'd create another join table similar to your staffs_events table, but for members. Within that model you'd need to do the same belongs_to association as with Event where you specify the class_name for the member.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top