ruby on rails one-to-many relationship
- by fenec
I would like to model a betting system relationship using the power of rails.
so lets start with doing something very simple modelling the relationship from a user to a bet.i would like to have a model bet with 2 primary keys.
here are my migrations
enter code here
class CreateBets < ActiveRecord::Migration
def self.up
create_table :bets do |t|
t.integer :user_1_id
t.integer :user_2_id
t.integer :amount
t.timestamps
end
end
def self.down
drop_table :bets
end
end
class CreateUsers < ActiveRecord::Migration
def self.up
create_table :users do |t|
t.string :name
t.timestamps
end
end
def self.down
drop_table :users
end
end
the models
enter code here
class Bet < ActiveRecord::Base
belongs_to :user_1,:class_name=:User
belongs_to :user_2,:class_name=:User
end
class User < ActiveRecord::Base
has_many :bets, :foreign_key =:user_1)
has_many :bets, :foreign_key =:user_2)
end
when i test here in the console my relationships I got an error
enter code here
u1=User.create :name="aa"
= #
u2=User.create :name="bb"
= #
b=Bet.create(:user_1=u1,:user_2=u2)
*****error*****
QUESTIONS:
1 How do I define the relationships between these tables correctly?
2 are there any conventions to name the attributes (ex:user_1_id...)
thank you for your help