I have a simple Rails 3 application that has a number of models. A simple overview of the models I’m having trouble with is:
client model
has_many :animals
animal model
belongs_to :client
What I would to be able to do is show a list of other animals that are owned by the same client.
Something like this:
<% @client.animals.each do |animal| %>
<%= animal.AnimalName %>
<% end %>
As this is within the Animal controller, my example code won’t work. Any pointers would be appreciated.
Update
To clarify, if I have the following records:
Danny (Client)
Cat (animal owned by Danny)
Dog (animal owned by Danny)
Rabbit (animal owned by Danny)
and I then went to the show view of the Dog’s record, I would like a list that would show all animals that Danny owned. E.g.
Cat
Dog
Rabbit
Ideally excluding the currently viewed animal (in this case dog).
I have tried the following but it doesn’t seem to work:
<% @client.animals.each do |client| %>
<%= @client.animal.AnimalName %>
<% end %>
If I understand you correctly you have
@animaland want to show all the animals owned by the owner of@animal. This can be done like this:Update:
You can just add a
.whereonto@animal.client.animals:It’s not such a good idea to do this in a view. So I would add an instance method to my Animal model:
With this you can do: