未创建关联模型

时间:2011-10-19 02:15:26

标签: ruby-on-rails activerecord model

我是一个完整的铁杆新手,所以请原谅我,如果这是微不足道的。

我有一个属于商店或旅行派对的库存模型:

class Inventory < ActiveRecord::Base
  belongs_to :trader, :polymorphic => true
end

class Store < ActiveRecord::Base
    has_one :inventory, :as => :trader, :dependent => :destroy
end

class TravelingParty < ActiveRecord::Base

    has_many :travelers, :dependent => :destroy
    has_one :inventory, :as => :trader, :dependent => :destroy
    validates_presence_of :speed, :ration, :position
    accepts_nested_attributes_for :travelers, :reject_if => :reject_traveler, :allow_destroy => true
    accepts_nested_attributes_for :inventory, :allow_destroy => true

    def reject_traveler(attributes)
       attributes['profession'].blank? and attributes['name'].blank?
    end

end

我创建了一个表单,在提交时会创建一个旅行派对和一些旅行者。现在我希望表单也创建一个Inventory并将所有变量初始化为0.我知道以下内容并不解决变量初始化,但它似乎甚至没有将一行空值放入Inventory数据库表中

class TravelingPartiesController < ApplicationController

    def new
        @traveling_party = TravelingParty.new
        5.times do
            traveler = @traveling_party.travelers.build
        end
        @inventory = @traveling_party.inventory.create

    end

    def create
        @traveling_party = TravelingParty.new(params[:traveling_party])
        if @traveling_party.save
            flash[:notice] = "Successfully created traveling party and travelers."
            redirect_to '/store/'
        else
            flash[:error] = "Please specify a leader."
            redirect_to '/new/'
        end
    end

    def index
    end

end

为了更好地衡量,这是数据库模式的样子:

ActiveRecord::Schema.define(:version => 20111018224808) do

  create_table "inventories", :force => true do |t|
    t.integer  "ox"
    t.integer  "food"
    t.integer  "clothing"
    t.integer  "ammunition"
    t.integer  "money"
    t.integer  "axle"
    t.integer  "wheel"
    t.integer  "tongue"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "trader_id"
  end

  create_table "stores", :force => true do |t|
    t.string   "name"
    t.integer  "location"
    t.integer  "priceScale"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

# Could not dump table "travelers" because of following StandardError
#   Unknown type 'relations' for column 'traveling_party_id'

  create_table "traveling_parties", :force => true do |t|
    t.integer  "speed"
    t.integer  "ration"
    t.integer  "position"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

end

库存数据库表是否完全没有受到影响?一旦有效,初始化travel_party.inventory以获得全部0的最佳方法是什么? (即牛,食物,衣服等的价值)。

1 个答案:

答案 0 :(得分:0)

这可能是因为您的库存表中不包含'trader_type'。这是多态关联所必需的。

  create_table "inventories", :force => true do |t|
    t.integer  "trader_id"
    t.string   "trader_type"
  end

编辑:

要将所有值初始设置为0,最好的方法是将默认值放在表格中的字段中。 (如果你希望它总是被初始化为0,如果没有其他选项,否则它们将默认为零)

我相信您可以使用

创建迁移
change_table(:inventories) do |t|
  t.change :ox, :integer, :default => 0
end