Apollo
Apollo

Reputation: 1986

Simple RoR relationship in the view

I am studying Ruby on Rails and I am trying to make this simple blog system using devise to create the login part.

This question must have a very simple answer, but I cannot find it using google, so I finally gave up and decided to ask it here.

I have a Users table created by devise and a Posts table created by a scaffold command.

The Posts table has a user_id field. In the creation of a post, I use this code:

  def create
    @post = Post.new(params[:post])
    @post.user_id = current_user.id

    respond_to do |format|
      if @post.save
        format.html { redirect_to @post, notice: 'Post was successfully created.' }
        format.json { render json: @post, status: :created, location: @post }
      else
        format.html { render action: "new" }
        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
  end

This way I get the user id and create this relationship.

This is my Post model:

class Post < ActiveRecord::Base
  attr_accessible :body, :title, :user_id

  belongs_to :user

end

Now, all I want is to show the name of the author in the list method.

I tried several things and none seem to get things done.

How do I link the user name to the post instead of the user id?

My current index method is the standard one:

  def index
    @posts = Post.all

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @posts }
    end
  end

I know I need to add parameters in that Post.all thing, but how?

Thanks!

Note: I use rails 3 and PostgreSQL.

Upvotes: 0

Views: 58

Answers (2)

user1454117
user1454117

Reputation:

You can access the user object through the relationship:

@post.user.name

If you want to eager load the relationship, you can change your @posts = Post.all statement to the following:

@posts = Post.includes(:user)

Upvotes: 1

Jakob S
Jakob S

Reputation: 20125

Assuming the user name is in User#name, you can display it by adding something like this to your view:

<%= post.user.name %>

Your posts/index.html.erb view probably has some code ala

<% @posts.each do |post| %>
  <tr>
    <td><%= post.name %></td>
    ...
  </tr>
<% end %>

Adding another table cell with the author name could make it look like:

<% @posts.each do |post| %>
  <tr>
    <td><%= post.name %></td>
    <td><%= post.user.name %></td>
  </tr>
<% end %>

Upvotes: 0

Related Questions