Help With associations

I am having some problems manipulating associations. For example, I have
an opinion model that belongs to both a user model and a blog model.
When listing a users blogs I want to also list that users opinion of the
blog. So in my view/blogs/list, I have some code like this:

<% @op = blog.opinions(:user_id => current_user.id)%>
<%= h(@op.rating)%>

rating is the field name in my opinions table. This however returns me
the following error message:

undefined method `rating’ for Opinion:Class

Since I do have a rating field in my opinions table, I’m not exactly
sure what is wrong with this. Thanks,
Charlie

did you put
attr_accessor :rating
at the start of your opinion class ? This makes the rating getter and
setter available for other classes
HTH,

Elise

On Aug 11, 11:00 pm, Charlie W. [email protected]

Hmm,
I just put that at the beginning of my opinion model and it still
didn’t work.
Also, I had never heard about attr_accessor before, ill have to look
into it.

[email protected] wrote:

did you put
attr_accessor :rating
at the start of your opinion class ? This makes the rating getter and
setter available for other classes
HTH,

Elise

On Aug 11, 11:00 pm, Charlie W. [email protected]

Thanks,
Could someone provide me with a simple explanation on when to use
instance variables vs. when not to?

For starters … the @op variable does not need to have the “@” symbol
inside the view. That makes it an “instance” …

2nd … you’re not getting back an “Opinion” object where you do
“blog.opinions( … )” you’re getting back an “array of opinion”
objects.

You need to do something similar to this …

<% opinions = blog.opinions( :user_id => current_user.id ) %>

<% for opinion in opinions %>

<%= h( opinion.rating ) %> <% end %>

Hope that helps, man.

Good luck.

On Aug 11, 4:00 pm, Charlie W. [email protected]

Charlie W. wrote:

Thanks,
Could someone provide me with a simple explanation on when to use
instance variables vs. when not to?

HI Charlie,

I had written this in response to a question here. It doesn’t
specifically address instance variables but gives the general feeling
about what they do.
http://groups.google.com/group/rubyonrails-talk/browse_thread/thread/2ae42439587d32b9/4e71bbb39243f06e?l#4e71bbb39243f06e

Hopefully this will give you some idea. If it doesn’t, I hope that
someone can give you a better explanation :slight_smile:

Cheers,
Mohit.
8/13/2007 | 9:18 AM.