【问题标题】:Rails fixtures :has_many and :belongs_toRails 固定装置 :has_many 和 :belongs_to
【发布时间】:2014-03-27 22:05:44
【问题描述】:

如何在我的 .yml 中为 has_many 和 belongs_to 变量创建示例数据。

这是一个将这些文件添加到终端中的简单 rails new lab 命令中的示例。我真的不知道如何用英语解释这个。但我希望我的代码能显示足够的细节来理解这一点。

man.rb

class Man < ActiveRecord::Base
  attr_accessible :name
  has_many :items
end

item.rb

class Item < ActiveRecord::Base
  attr_accessible :name
  belongs_to :man
end

men.yml

one:
  name: ManOne
  #items: one, two

two:
  name: ManTwo
  #items: one, two

items.yml

one:
  name: ItemOne

two:
  name: ItemTwo

man_test.rb

require 'test_helper'

class ManTest < ActiveSupport::TestCase
  def test_man
    Man.all.each do |man|
      puts man.name.to_s + ": " + man.items.to_s
    end
    assert true
  end
end

【问题讨论】:

    标签: ruby-on-rails ruby fixtures


    【解决方案1】:

    看看灯具docs,你可以做一些类似的事情:

    men.yml

    man_one:
      name: ManOne
    
    man_two:
      name: ManTwo
    

    items.yml

    item_one:
      name: ItemOne
      man: man_one
    
    item_two:
      name: ItemTwo
      man: man_one
    
    item_three:
      name: ItemThree
      man: man_two
    

    更新

    您的表column 中似乎没有man_id。为此,您应该创建一个迁移:

    rails g migration AddManIdToItem man_id:integer
    

    并运行迁移:bundle exec rake db:migrate

    【讨论】:

    • 我添加了您所做的更改。然后我确实将 men(:man_one).items 放入了 man_test.rb 我得到了一个错误
    • ActiveRecord::StatementInvalid: SQLite3::SQLException: table items has no column named man_id: INSERT INTO "items" ("name", "created_at", "updated_at", "id", "man_id ") 值('ItemOne'、'2014-03-27 23:09:59'、'2014-03-27 23:09:59'、494534085、82093985)
    • 项目中没有 man_id 列。我已经更新了答案。
    【解决方案2】:

    我相信您是在询问固定装置。你这样做:

    #men.yml
    first_man:
      name: 'One'
    
    #items.yml
    first_item:
      name: 'First item'
      man: first_man
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-20
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 2014-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多