开发者

Using ActiveRecord.create with belongs_to associations

开发者 https://www.devze.com 2023-04-05 13:09 出处:网络
I\'m using Rails 3.1 and have a simple transaction class that references a User model: class User < ActiveRecord::Base

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 misunderstandin开发者_如何转开发g 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_accessible line in the Transaction model to

attr_accessible :amount, :sender, :recipient

and all is well.

0

精彩评论

暂无评论...
验证码 换一张
取 消