为什么Rails在它应该是单数时会产生多元关联?

时间:2016-01-22 03:00:11

标签: mysql ruby-on-rails ruby associations

这些是我的迁移:

主题迁移

class CreateSubjects < ActiveRecord::Migration
  def up
    create_table :subjects do |t|
      t.string "subject_name" , :limit => 25
      #some Values here
    end
  end
  def down 
    drop_table :subjects
  end
end

页面迁移

class CreatePages < ActiveRecord::Migration
  def up
    create_table :pages do |t|
      t.string "page_name" , :limit => 25
      #some Values here
    end
    add_index("pages", "permalink")
    add_reference :pages, :subjects, index: true, foreign_key: true
  end
  def down
    drop_table :pages
  end
end

现在模特:

class Subject < ActiveRecord::Base
  has_one :page
end

和Page模型:

class Page < ActiveRecord::Base
  belongs_to :subject
end

在rails控制台中,我创建了一个新主题,应该允许我运行此命令:

s = Subject.find(1) 
s.page

运行此操作后,我收到一条SQL错误,指出列page.subject_id不存在。 Rails自己处理复数和单数。所以我创建了一个页面来检查SQL命令,这就是显示的内容:

  

页面ID:nil,page_name:nil,永久链接:nil,visible:true,created_at:nil,updated_at:nil,subjects_id:nil

所以铁轨似乎错误地创造了这个列; subjects_id是Pages表上的列,但是在页面中搜索与某个Subject相关的列的自动生成的SQL命令将作为复数传递。

帮助。

1 个答案:

答案 0 :(得分:0)

您的迁移似乎缺少一些细节。我建议查看Rails guides has_one Active Record关联。

例如,给定一个活跃的记录模型:

 class Supplier < ActiveRecord::Base
   has_one :account
 end

关联的迁移可能显示为:

 class CreateSuppliers < ActiveRecord::Migration
   def change
     create_table :suppliers do |t|
       t.string :name
       t.timestamps null: false
     end

     create_table :accounts do |t|
       t.belongs_to :supplier, index: true
       t.string :account_number
       t.timestamps null: false
     end
   end
 end