I’m using Rails 3.1 and have a simple transaction class that references a User model:
class User < ActiveRecord::Base
has_many :transactions, :foreign_key => 'sender_id'
end
class Transaction < ActiveRecord::Base
belongs_to :sender, :class_name => 'User'
belongs_to :recipient, :class_name => 'User'
attr_accessible :amount
end
The database schema is
create_table "transactions", :force => true do |t|
t.decimal "amount"
t.integer "sender_id", :null => false
t.integer "recipient_id", :null => false
end
create_table "users", :force => true do |t|
end
I would like to create a set of initial transactions in the seeds.rb, but the underlying INSERT is never generated with foreign keys for the sender_id and recipient_id. The signature of the method is:
ruby-1.9.2-p290 :022 > Transaction.method(:create) =>
#<Method: Transaction(id: integer,
amount: decimal,
sender_id: integer,
recipient_id: integer)
(ActiveRecord::Base).create>
I’ve tried both
Transaction.create(
amount: 0.50,
sender: User.first,
recipient: User.last,
)
and
Transaction.create(
amount: 0.50,
sender_id: User.first.id,
recipient_id: User.last.id,
)
In each case, the INSERT statement is
SQL (0.6ms) INSERT INTO `transactions` (`amount`, `recipient_id`, `sender_id`)
VALUES (0.75, NULL, NULL)
I’m new to rails, so I’m sure this is a misunderstanding on my part, but I have not been able to find a solution from my reading of the rails docs.
Simple solution. I just needed to change the
attr_accessibleline in the Transaction model toand all is well.