使用一对多关联获取数据
我是 ror 新手。我有 2 个组表(称为“ab”)和子组(称为“cd”)。每个组都有几个子组。我定义了belongs_to和has_many关系。
模型 ab.rb
class Ab < ActiveRecord::Base
has_many:cds
end
模型 cd.rb
class Cd < ActiveRecord::Base
belongs_to :ab
end
ab 和 cd 有 2 列,分别称为 title 和 Dscr。我是否必须创建一个联接表 (ab_cd_join_table)
我想在视图中显示特定组及其子组。
视图的控制器
class DisplayController < ApplicationController
def index
@ab = Ab.find_by_title("XXXXXX")
@cds = @ab.cds
for cd in @cds
logger.info cd.title
end
我在视图中使用它。
显示视图
<%= @ab.title %>
我不知道如何显示属于该组=“XXXXXX”的不同子组的标题和Dscr
提前致谢
I am new to ror. I have 2 tables for group (called 'ab') and sub-group(called 'cd').Each group has several sub-groups.I have defined belongs_to and has_many relationship.
Model ab.rb
class Ab < ActiveRecord::Base
has_many:cds
end
Model cd.rb
class Cd < ActiveRecord::Base
belongs_to :ab
end
ab and cd have 2 columns each called title and Dscr.Do I have to create a join table (ab_cd_join_table)
I want to display a particular group and its sub-groups in a view.
The controller for the view
class DisplayController < ApplicationController
def index
@ab = Ab.find_by_title("XXXXXX")
@cds = @ab.cds
for cd in @cds
logger.info cd.title
end
I am using this in the view.
display view
<%= @ab.title %>
I don't know how to display the title and Dscr of different sub-groups belonging to the group = "XXXXXX"
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为您要求的是视图中的这个:
控制器中的这个:
这样您将显示与“XXXXXX”匹配的 ab-model 的所有 cd。
更新:
为了使belongs_to和has_many一起工作,具有belongs_to的模型需要有一列对应具有has_many的模型。在这种情况下,Cd 需要有一个名为 ab_id 的列。
cd.ab_id需要是对应Ab模型的id。
这也许应该在创建 Cd 对象时设置,但只是为了测试它,你可以这样做。
What I think you're asking for is this in the view:
and this in the controller:
That way you will display all cds for the ab-model matching "XXXXXX".
Update:
For belongs_to and has_many to work the model with belongs_to needs to have a column for the one that has has_many. In this case Cd needs to have a column named ab_id.
cd.ab_id needs to be the id of the corresponding Ab model.
This maybe should be set upon creation of a Cd object, but just to test it out you can do like this.
我是否必须创建一个连接表(ab_cd_join_table)
在视图中显示子组标题
另外,如果您总是需要带有组的子组,则通过使用 find 中的 include 选项将它们加载到一个查询中,就像
现在一样,您不需要显式计算 cd,只需使用提到的视图代码即可多于
Do I have to create a join table (ab_cd_join_table)
Displaying subgroup title in view
Also, if you alwas need sub_groups with group then load them in one query by using include option in find like
now you don't need to calculate cds explicitly just use the view code mentioned above