加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 02:50:04 所属栏目:百科 来源:网络整理
导读:鉴于以下内容,我如何在我的数据库中插入行? (或者我应该在我的架构中纠正什么?) 楷模: class Item ActiveRecord::Base has_many :tran_items has_many :transactions,:through = :tran_itemsendclass TranItem ActiveRecord::Base belongs_to :item belon
鉴于以下内容,我如何在我的数据库中插入行? (或者我应该在我的架构中纠正什么?)

楷模:

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控制台来测试.

解决方法

(编辑:模型名称“Transaction”可能会因ActiveRecord :: Transactions而导致一些问题. 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

(编辑:make belongs_to singular)

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

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>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读