2011-09-18 57 views
0

我用Rails 3.1,並有一個簡單的事務類引用一個用戶模式:有belongs_to的關聯使用ActiveRecord.create

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 

數據庫模式是

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 

我想在seeds.rb中創建一組初始事務,但從不生成底層INSERT,外鍵爲sender_idrecipient_id。該方法的簽名是:

ruby-1.9.2-p290 :022 > Transaction.method(:create) => 
    #<Method: Transaction(id: integer, 
         amount: decimal, 
         sender_id: integer, 
         recipient_id: integer) 
    (ActiveRecord::Base).create> 

我都試過

Transaction.create(
    amount:    0.50, 
    sender:    User.first, 
    recipient:    User.last, 
) 

Transaction.create(
    amount:    0.50, 
    sender_id:    User.first.id, 
    recipient_id:   User.last.id, 
) 

在每種情況下,INSERT聲明

SQL (0.6ms) INSERT INTO `transactions` (`amount`, `recipient_id`, `sender_id`) 
      VALUES (0.75, NULL, NULL) 

我'新的鐵路,所以我'我確定這是我的一個誤解,但是我一直沒有能夠從閱讀rails文檔中找到解決方案。

回答

2

簡單的解決方案。我只需要在交易模式attr_accessible線改爲

attr_accessible :amount, :sender, :recipient 

,一切都很好。