How can I access another collection of objects in a view in Rails?

I'm not sure how to look for this answer, so I'll go ahead and ask it.

In my rails project, I have a User model and a foo model. A user can have one or more foo models assigned to him. I accomplished this by adding

has_many :foo, :through => :user_foo

      

in my user model.

Now, in my opinion, I want to display a list of all foos. Not only the ones that are selected (I will be making these radio buttons, but that's a different question). When I try to do this (yes, I am using haml):

    - for foo in @foos

      

I am getting this error:

You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.each

      

My guess is that this is because the @foos collection is empty. How can I access this collection in my user view?

** edit **

I think my original question was a little confusing. the first problem I'm trying to figure out is how to access the foos collection from my custom view. the relationship doesn't matter. I just need a list of all foos on the system. and not just those assigned to the user.

0


source to share


3 answers


I assume you have a belongs_to :user

Foo in your class?

What does your controller code look like? To show all the foos it should have something like this:



def index
  @foos = Foo.all
end

      

+3


source


To access all Foos just use

@foos = Foo.all

      

in your controller.

The error you ran into before, the nil object error can be prevented by checking:

- if @foos.empty?
  %p There are no Foos
- else
  ...

      



Also, the best way to iterate over a collection is to use a method #each

, not a loop for

. For example:

- @foos.each do |foo|
  %p= foo.name

      

So a complete example:

- if @foos.empty?
  %p There are no Foos
- else
  - @foos.each do |foo|
    %p= foo.name

      

+2


source


The error indicates that the foo object is empty.

If you want all Foo to be associated with the current user object, you use

my_user = User.find(1) # finds user with id no. 1
list_of_foos = my_user.foos # finds all foos associated with my_user

      

must work

If you're looking for all foo regardless of their association, you use

list_of_foos = Foo.find(:all)

      

It might not be up to the Rails syntax that is currently in vogue: it's been a while since I've been actively developing Rails, but this, if I understood the question correctly, should help you. Good luck.

0


source







All Articles