Lindsiria
Lindsiria

Reputation: 187

ActiveRecord Associations: Getting data through multiple tables

I am having a problem with my Active Record Associations and was wondering if someone could point me in the right direction. I will try the best to explain my problem, but I'm not even sure what to title it.

I have three tables in my database that are all interconnected and I need to call information from each of the three tables within one view file.

There can be multiple posts within a topic, each post (and topic) has one user attached to it. I need to be able to call data in the User table using Post and Topics.

Question: How to get data from a table through multiple Models. (Topic -> Post -> User)

The Models

class Topic < ActiveRecord::Base
    belongs_to :forum
    has_many :posts, :dependent => :destroy  
    belongs_to :user
end

class Post < ActiveRecord::Base  
    belongs_to :topic  
    belongs_to :user
end

class User < ActiveRecord::Base
    has_many :topics
    has_many :posts, through: => :topics
end

In the View/Topics/show.html, I am trying to show the user who posted. When I try to get the information, it is giving me errors of undefined methods for "name". What I want is something like:

http://i44.tinypic.com/1z4kapj.png

Example: Post 1 was created by UserName

View/Topics/Show.html.erb

<% @topic.posts.each do |post| %>
    <tr>
        <td class="subforum" width="80%">
            <%= post.created_at %>
            <div class="go-right">
                <%= link_to 'Edit', edit_post_path(@post) %> 
            </div>
        </td>
    </tr>

    <tr>
        <td class="row1">
            <%= post.users.name %>
            <%= post.user_id %>
        </td>
    </tr>
    <tr>
        <td class="row1">
            <%= post.content %>
        </td>
    </tr>
<% end %>

Upvotes: 0

Views: 1106

Answers (1)

Paul Richter
Paul Richter

Reputation: 11072

You're doing it correctly, except that you should be invoking post.user, instead of post.users.

In your Post model, you have a line belongs_to :user. This means that the Post model has a single User object. Meaning, you access the dependent object via the singular form of the association name, in this case simply .user. If you use the pluralized form with this kind of relationship, you get back a useless(in this case) collection proxy which, as you've seen, does not behave the same as your object.

If you had something like has_many :users, then you would indeed use the pluralized .users, and you'd get a collection of User objects, in the same was as Topics.posts gives you a collection Post objects.

ALSO:

In this line: link_to 'Edit', edit_post_path(@post), ditch the @ symbol, it should be link_to 'Edit', edit_post_path(post). Remember that this symbol refers to an instance variable, which is completely different than a local scope variable of the same name (in other words @post != post).

Hope that helps.

Upvotes: 2

Related Questions