将 ActiveRecord.create 与Belongs_to 关联一起使用
我正在使用 Rails 3.1,并且有一个引用用户模型的简单事务类:
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_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 文档的阅读中找到解决方案。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
简单的解决方案。我只需要将 Transaction 模型中的
attr_accessible
行更改为,一切都很好。
Simple solution. I just needed to change the
attr_accessible
line in the Transaction model toand all is well.