开发者

Find items with belongs_to associations in Rails?

开发者 https://www.devze.com 2023-01-02 13:00 出处:网络
I have a model called Kase each \"Case\" is assigned to a contact person via the following code: class Kase < ActiveRecord::Base

I have a model called Kase each "Case" is assigned to a contact person via the following code:

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开发者_Python百科_id"

I was wondering if it is possible to list on the contacts page all of the kases that that person is associated with.

I assume I need to use the find command within the Person model? 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?


Maybe following will work:

@person.kase.conditions({:person_id => some_id})

where some_id is an integer value.

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.

   <% 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

@kases = Person.find(person_id).kases

Assuming person_id has the id of the person that you want to see the cases for.


You would probably want something like

has_many :kases

in your Person model, which lets you do @kases = Person.find(person_id).kases

as well as everything else that has_many enables.

An alternate method would be to go through Kase directly:

@kases = Kase.find_all_by_person_id(person_id)

0

精彩评论

暂无评论...
验证码 换一张
取 消