Rails的两个表的连接:如何选择属性 [英] Rails join from two table: how select attribute
问题描述
在Rails 3.2.1
In Rails 3.2.1
我有:
class Project < ActiveRecord::Base
attr_accessible :name, :description
has_many :subprojects
end
class SubProject < ActiveRecord::Base
attr_accessible :id_name, :description, :num_alloc, :project_id
belongs_to :projects
end
我怎样才能返回Rails控制器,包含name属性(从项目模型)一个对象,并在 ID_NAME
,说明
和 num_alloc
(从子项目模型)。
How can i return in a rails controller, an object that contain the "name" attribute (from the Project model) and the id_name
, description
and num_alloc
(from the SubProject model).
在控制器中,如果我做
@results= SubProject.joins('LEFT OUTER JOIN.......)
@Results
包含子项目只有类的属性,因为 SubProject.joins(...)
返回的子项目
异议的权利?
@results
contains only the attribute of the SubProject class because SubProject.joins(...)
returns an SubProject
object right?
所以,如何从两个模型属性返回一个对象?
So how can i return an object with attribute from the two model?
推荐答案
我将在你的模型定义开始:你的的has_many
协会需要有在名称中的下划线 - 子项目 - &GT; sub_project
:
I would start at your model definitions: Your has_many
association needs to have an underscore in the name - SubProject -> sub_project
:
class Project < ActiveRecord::Base
attr_accessible :name, :description
has_many :sub_projects # !
end
接下来,你的 belongs_to的
需要在单数形式:
class SubProject < ActiveRecord::Base
attr_accessible :id_name, :description, :num_alloc, :project_id
belongs_to :project # !
end
在你做这些改变,你可以查询:
After you make these changes, you can query:
@sub_projects = SubProject.includes(:project).all
name = @sub_projects.first.project.name
...
这篇关于Rails的两个表的连接:如何选择属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!