Reputation: 179
I'm trying to achieve the following, relationships and object calls and wondering if I need a separate table and how those associations would work.
A User can leave many notes (user.notes) A Note can have one Sender (note.sender)
A User can receive many notes (user.notes). A Note can have many receivers (notes.recipient). A Note can be viewed_at by a recipient.
A user can select a recipient. A user can select many recipients.
A recipient can view each note once. Once all the recipients of the note have viewed the note the note will be destroyed.
My schema looks like this:
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :first
t.string :last
t.string :email
t.string :username
t.string :pw
t.string :devicetoken
t.timestamps
end
end
end
class CreateNotes < ActiveRecord::Migration
def change
create_table :notes do |t|
t.integer :user_id
t.integer :recipient_id
t.text :note_text
t.datetime: viewed_at
t.datetime :expiration
t.timestamps
end
end
end
My Models Look Like this:
class User < ActiveRecord::Base
has_many :notes
end
class Note < ActiveRecord::Base
belongs_to :user, foreign_key: 'user_id', class_name: 'User'
belongs_to :user, foreign_key: 'recipient_id', class_name: 'User'
end
I can't pull up the recipient ids of the notes however, and I can't tell which recipient have viewed the note.
Upvotes: 1
Views: 89
Reputation: 4562
I suspect you're having trouble because you are defining two belongs_to for the same symbol. Try doing this instead:
class Note < ActiveRecord::Base
belongs_to :user, foreign_key: 'user_id', class_name: 'User'
belongs_to :recipient, foreign_key: 'recipient_id', class_name: 'User'
end
Then try calling note.recipient
Upvotes: 1