将ActiveRecord.create与belongs_to关联一起使用

时间:2011-09-18 20:54:24

标签: ruby-on-rails activerecord foreign-keys associations

我正在使用Rails 3.1并且有一个引用User模型的简单事务类:

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中创建一组初始事务,但永远不会使用INSERTsender_id的外键生成基础recipient_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的新手,所以我确信这是我的一个误解,但是我无法通过阅读rails docs找到解决方案。

1 个答案:

答案 0 :(得分:2)

简单的解决方案。我只需要将事务模型中的attr_accessible行更改为

attr_accessible :amount, :sender, :recipient

一切都很顺利。