【问题标题】:rails undefined method 'has_many'导轨未定义的方法'has_many'
【发布时间】:2012-11-12 19:21:04
【问题描述】:

我正在制作数据库:

class CreateUsers < ActiveRecord::Migration
  def change
    has_many :listings, :dependent => :restrict #won't delete if listings exist
    has_many :transactions, :dependent => :restrict #won't del if trans exist
    create_table :users do |t|
      t.integer :key #it's hard to use string as primary
      t.string :identifier_url
      t.string :username
      t.integer :rating

      t.timestamps
    end
  end
end

class CreateListings < ActiveRecord::Migration
  def change
    has_one :book
    belongs_to :transaction
    belongs_to :user
    create_table :listings do |t|
      t.integer :key
      t.integer :condition
      t.decimal :price

      t.timestamps
    end
  end
end

我在任何地方都找不到任何东西,所以我猜这是非常基本的东西。

【问题讨论】:

    标签: ruby-on-rails migration rake migrate


    【解决方案1】:

    关联(has_many、belongs_to 等)应该在模型中声明,而不是在迁移中。

    这是从迁移开始的好读物: http://guides.rubyonrails.org/migrations.html

    还有这个用于关联: http://guides.rubyonrails.org/association_basics.html

    【讨论】:

    • 但是要在模型中使用“belongs_to :user”,表中必须有一列 user_id ?!?
    • @Klaus,是的,当然。如果您使用生成器来创建模型,那么该列已经为您准备好了
    【解决方案2】:

    将您的关联放入模型中

    class Member < ActiveRecord::Base
    
    has_many :listings, :dependent => :restrict 
    has_many :transactions, :dependent => :restrict
    
    end
    

    【讨论】:

      【解决方案3】:

      您不必在迁移中声明关联,而是在模型中声明!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多