rails中的has_many关联不返回子行

时间:2012-11-28 00:02:48

标签: ruby-on-rails

class Department < ActiveRecord::Base

attr_accessible :Department_Id, :DepartmentName,:LocationID
set_primary_key :Department_Id 
has_many :Employee

end

rails console:

dept=Department.find(50)
dept.Employee 
SELECT `employees`.* FROM `employees` WHERE `employees`.`Department_Id` IS NULL

为什么它用NULL附加where子句,我期待看到50.我做错了什么

2 个答案:

答案 0 :(得分:0)

在ruby中,以大写字母开头的变量是常量变量。您的代码应更改为:

class Department < ActiveRecord::Base

attr_accessible :department_id, :department_name,:location_id
has_many :employees

end

更新:我刚才举了一些例子。您需要相应地更改所有变量,数据库列名称等。请确保一切符合规则:常量变量以大写字母和局部变量开头,实例变量全部为小写,其中单词用短划线分隔。

如果您的代码符合规则,则无需致电set_primary_key并为belongs_to关联设置foreign_key

答案 1 :(得分:0)

你必须遵循适当的约定,大写字母变量意味着常数变量,尝试如下

class Department < ActiveRecord::Base

  attr_accessible :Department_Id, :DepartmentName,:LocationID
  set_primary_key :Department_Id 
  has_many :employee

end

如果你做的话甚至更好

class Department < ActiveRecord::Base

  attr_accessible :department_id, :department_name,:location_id
  set_primary_key :department_id 
  has_many :employee

end