I have a User Model and a through table between user's called Invite Model.
I want users to be able to invite others, be invited and have the association created.
My migration file looks like this:
class CreateInvites < ActiveRecord::Migration
def change
create_table :invites do |t|
t.integer :invited_id
t.integer :inviter_id
t.timestamps
end
end
In my Invite Model I have the following:
class Invite < ActiveRecord::Base
belongs_to :invited, :class_name => 'User'
belongs_to :inviter, :class_name => 'User'
end
I am unsure how to construct the user model with the appropriate associations. I want to a User to belong to one inviter and have many inviteds. How should I update my User Model appropriately.
class User < ActiveRecord::Base
has_many :sent_invites, :class_name => "Invite", :foreign_key => :inviter_id
has_many :inviteds, :through => :sent_invites
has_one :invite, :foreign_key => :invited_id
has_one :inviter, :through => :invite
end
Sidebar, it is generally a good idea to add indexes to foreign keys like so:
class CreateInvites < ActiveRecord::Migration
def change
create_table :invites do |t|
t.references :invited
t.references :inviter
t.index :invited_id
t.index :inviter_id
t.timestamps
end
end
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.