【问题标题】:Ruby On Rails scaffold need to include foreign keys?Ruby On Rails 脚手架需要包含外键吗?
【发布时间】:2015-01-04 04:55:10
【问题描述】:

我正在学习 ruby​​ on rails 的基础知识,我想进行一些简单的查询,但我有疑问:

我将拥有这些模型:

class Client < ActiveRecord::Base
  has_one :address
  has_many :orders
  has_and_belongs_to_many :roles
end

class Address < ActiveRecord::Base
  belongs_to :client
end

class Order < ActiveRecord::Base
  belongs_to :client, counter_cache: true
end

class Role < ActiveRecord::Base
  has_and_belongs_to_many :clients
end

现在,我将使用脚手架来生成所有东西,我想知道是否必须将外键直接放在脚手架中,例如:

rails 生成脚手架地址 street:string number:integer client_id:integer

或者当我建立这些关联然后迁移我的数据库时,它们将是隐式的?

我不知道我是否以最好的方式解释自己。

谢谢

【问题讨论】:

  • 是的,首先你应该生成父模型脚手架,然后你可以生成子脚手架并像上面一样指出外国
  • rails g 脚手架客户端 client_name:string rails g 脚手架地址 client_id:integer address1:string like this
  • 所以,如果我生成:Adress street:string number:integer 它永远不会与任何客户相关联,即使我写了:belongs_to :client 在客户的模型中正确吗?
  • 是的,您需要将 client:reference 添加到上述命令。
  • 看看下面的答案会有帮助

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4 ruby-on-rails-3.1


【解决方案1】:

rails 4 中,您可以这样使用 belongs_to:

假设您的应用程序中有一个用户模型

rails g scaffold comment belongs_to:user text:string

它会在您的迁移文件夹中生成该类:

class CreateComments < ActiveRecord::Migration
  def change
    create_table :comments do |t|
      t.string :text
      t.belongs_to :user, index: true, foreign_key: true
      t.timestamps null: false
    end
  end
end

您应该执行rake db:migrate 然后,此命令将user_id 属性创建为数据库表中的索引列。

【讨论】:

    【解决方案2】:

    是的,没有参考。您需要传递 client_id 或对 Client 模型的引用,例如:

    rails generate scaffold Address street:string number:integer client_id:integer:index 
    

    rails generate scaffold Address street:string number:integer client:references
    

    【讨论】:

      猜你喜欢
      • 2021-09-18
      • 2015-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-21
      • 2010-09-20
      • 2011-10-09
      • 2013-11-06
      相关资源
      最近更新 更多