I have a model Person and one Organisation. A Person can belong to any
number of Organisations and an Organisation can have any number of
Persons attributed to it. As below:
====
class Person < ActiveRecord::Base
has_many :person_organisations, :dependent => true
has_many :organisations, :through => :person_organisations
end
class Organisation < ActiveRecord::Base
has_many :person_organisations, :dependent => true
has_many :persons, :through => :person_organisations
end
I’m writing an action on my Person controller called
‘list_by_organisation’ which will return all the contacts from a
specified organisation. How do I achieve this?
Do I do something like the following? But what goes in the condition?
You need either has_and_belongs_to_many (if the join table has no
attributes), in which case you don’t need :through (AR does all that for
you), or if the join table has attributes (e.g. date of joining) you
need to declare that as a model (in which case I’d prob just call it
membership).
In your Person controller you could do something like @organisations =
Organisation.find(:all, :include => :persons) if you want all the
organisations, and then in your view iterate through them:
<% @organisations.each do |organisation| %>
<%= h(organisation.title) %>
organisation.persons.each do |person|
<%= h(person.name) %>
<% end %>
<% end %>
or if you just want members of a specific organisation (identified by,
say, params[:organisation_id]) @persons = Organisation.find(params[:organisation_id]).persons
Or something like that.
HTH
CT
p.s. I think rails by default uses people as the plural of persons (so
should be has_many :people, not has_many :persons, ditto all the other
persons)
You need either has_and_belongs_to_many (if the join table has no
attributes), in which case you don’t need :through (AR does all that for
you), or if the join table has attributes (e.g. date of joining) you
need to declare that as a model (in which case I’d prob just call it
membership).
Yep.
In your Person controller you could do something like @organisations =
Organisation.find(:all, :include => :persons) if you want all the
organisations, and then in your view iterate through them:
<% @organisations.each do |organisation| %>
<%= h(organisation.title) %>
organisation.persons.each do |person|
<%= h(person.name) %>
<% end %>
<% end %>
or if you just want members of a specific organisation (identified by,
say, params[:organisation_id]) @persons = Organisation.find(params[:organisation_id]).persons
or if you just want members of a specific organisation (identified by,
say, params[:organisation_id]) @persons = Organisation.find(params[:organisation_id]).persons
That worked many thanks!
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.