ruby-on-rails - 使用多对多关系时如何插入行

标签 ruby-on-rails model schema insert

鉴于以下内容,我如何在我的数据库中插入行? (或者我应该在我的模式中更正什么?)

楷模:

class Item < ActiveRecord::Base
    has_many                            :tran_items
    has_many :transactions, :through => :tran_items
end
class TranItem < ActiveRecord::Base
    belongs_to :item
    belongs_to :transaction
end
class Transaction < ActiveRecord::Base #answer: rename Transaction
    has_many                            :tran_items
    has_many :items, :through =>        :tran_items
end

架构:
create_table :items do |t|
  t.references :tran_items #answer: remove this line
  t.string     :name
end
create_table :tran_items do |t|
  t.belongs_to :items,  :transactions,  :null => false #answer: unpluralize
  t.integer    :quantity
end
create_table :transactions do |t|
  t.references :tran_items #answer: remove this line
  t.decimal    :profit
end

我花了几个小时试图插入记录,使用 rails 控制台来测试。

最佳答案

(编辑:由于 ActiveRecord::Transactions,模型名称“Transaction”可能会给您带来一些问题。There is a lighthouse ticket。)

您的架构设置不正确。 “references”是“belongs_to”的别名。项目和交易不属于 trans_items,他们每个 has_many trans_items(根据您的型号)

create_table :items do |t|
  t.string     :name
end
create_table :tran_items do |t|
  t.belongs_to :item, :transaction, :null    => false
  t.integer    :quantity
end
create_table :transactions do |t|
  t.decimal    :profit,  :default => 0
end

(编辑:使belongs_to 单数)

您是否删除了数据库并重新运行迁移以构建新模式?

rake db:drop && rake db:create && rake db:migrate

这是我在控制台中得到的:
>> i = Item.create(:name => 'My Item')    
=> #<Item id: 2, name: "My Item">
>> t = Transaction.create(:profit => 100)
=> #<Transaction id: 2, profit: #<BigDecimal:2411d2c,'0.1E3',4(8)>>
>> t.tran_items.create(:item => i)
=> #<TranItem id: nil, item_id: 2, transaction_id: 2, quantity: nil>

关于ruby-on-rails - 使用多对多关系时如何插入行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/285456/

相关文章:

ruby-on-rails - 需要 redis 时,rails 控制台返回 false

c++ - 如何使用 C++ 在 TensorFlow 中保存模型

mongodb - 环回: Saving one-to-many relations in MongoDB

model - 我可以在运行时更改报表模型的数据源吗

简单类型字符串的 XML 模式不区分大小写枚举

ruby-on-rails - 使用 Rails 和 Postgres 设置 travis.ci

javascript - Ruby on Rails jQuery 与 tokenInput gem 相关的问题

ruby-on-rails - 事件管理员自定义过滤器。按天过滤日期 |月 |日期属性的年份

java - 有没有像 Schematics (Python) for Java 这样的工具?

node.js - Mongoose Schema 的 ObjectId 默认值