Skip to content

Instantly share code, notes, and snippets.

@veezus
Created June 20, 2012 13:45
Show Gist options
  • Save veezus/2959954 to your computer and use it in GitHub Desktop.
Save veezus/2959954 to your computer and use it in GitHub Desktop.
ActiveRecord::Schema.define(:version => 20120620132905) do
create_table "tasks", :force => true do |t|
t.string "name"
t.integer "sender_id"
t.integer "receiver_id"
end
create_table "users", :force => true do |t|
t.string "name"
end
end
class Task < ActiveRecord::Base
attr_accessible :name, :receiver, :sender
belongs_to :sender, :class_name => 'User'
belongs_to :receiver, :class_name => 'User'
end
class User < ActiveRecord::Base
attr_accessible :name
has_many :sent_tasks, :class_name => 'Task',
:foreign_key => 'sender_id', :inverse_of => :sender
has_many :received_tasks, :class_name => 'Task',
:foreign_key => 'receiver_id', :inverse_of => :receiver
end
1.9.3p194 > User.create! :name => 'First'
=> #<User id: 1, name: "First">
1.9.3p194 > User.create! :name => 'Second'
=> #<User id: 2, name: "Second">
1.9.3p194 > Task.create! :name => 'Task 1', :sender => User.first, :receiver => User.last
=> #<Task id: 1, name: "Task 1", sender_id: 1, receiver_id: 2>
1.9.3p194 > User.first.sent_tasks
=> [#<Task id: 1, name: "Task 1", sender_id: 1, receiver_id: 2>]
1.9.3p194 > User.first.received_tasks
=> []
1.9.3p194 > User.last.sent_tasks
=> []
1.9.3p194 > User.last.received_tasks
=> [#<Task id: 1, name: "Task 1", sender_id: 1, receiver_id: 2>]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment