[英]Find items with belongs_to associations in Rails?
I have a model called Kase each "Case" is assigned to a contact person via the following code: 我有一个称为Kase的模型,每个“案例”通过以下代码分配给联系人:
class Kase < ActiveRecord::Base
validates_presence_of :jobno
has_many :notes, :order => "created_at DESC"
belongs_to :company # foreign key: company_id
belongs_to :person # foreign key in join table
belongs_to :surveyor,
:class_name => "Company",
:foreign_key => "appointedsurveyor_id"
belongs_to :surveyorperson,
:class_name => "Person",
:foreign_key => "surveyorperson_id"
I was wondering if it is possible to list on the contacts page all of the kases that that person is associated with. 我想知道是否可以在联系人页面上列出与该人相关联的所有Kases。
I assume I need to use the find command within the Person model? 我假设我需要在Person模型中使用find命令? Maybe something like the following?
也许像下面这样?
def index
@kases = Person.Kase.find(:person_id)
or am I completely misunderstanding everything again? 还是我完全误解了一切?
Thanks, 谢谢,
Danny 丹尼
EDIT: 编辑:
If I use: 如果我使用:
@kases= @person.kases
I can successfully do the following: 我可以成功执行以下操作:
<% if @person.kases.empty? %>
No Cases Found
<% end %>
<% if @person.kases %>
This person has a case assigned to them
<% end %>
but how do I output the "jobref" field from the kase table for each record found? 但是,如何为找到的每个记录从kase表中输出“ jobref”字段?
Maybe following will work: 也许下面的工作:
@person.kase.conditions({:person_id => some_id})
where some_id
is an integer value. 其中
some_id
是整数值。
Edit 编辑
you have association so you can use directly as follows: 您具有关联,因此可以直接使用,如下所示:
@kases= @person.kases
in your show.rhtml
you can use instance variable directly in your .rhtml also @kases
is an array so you have to iterate over it. 在
show.rhtml
您可以直接在.rhtml中使用实例变量。@ @kases
是一个数组,因此您必须对其进行迭代。
<% if @kases.blank? %>
No Kase found.
<% else %>
<% for kase in @kases %>
<%=h kase.jobref %>
<% end %>
<% end %>
If your person model has the association has_many :kases then, you can get all the cases that belongs to a person using this 如果您的人员模型具有关联has_many:kases,则可以使用此方法获取属于某个人员的所有案例
@kases = Person.find(person_id).kases
Assuming person_id has the id of the person that you want to see the cases for. 假设person_id具有您要查看案例的人员的ID。
You would probably want something like 您可能想要类似
has_many :kases
in your Person model, which lets you do @kases = Person.find(person_id).kases
在您的Person模型中,它可以让您执行
@kases = Person.find(person_id).kases
as well as everything else that has_many enables. 以及has_many启用的所有其他功能。
An alternate method would be to go through Kase directly: 另一种方法是直接通过Kase:
@kases = Kase.find_all_by_person_id(person_id)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.