Joe Dayvie
Joe Dayvie

Reputation: 314

Showing username with association with Rails

I've been researching but cannot seem to find the answer. All I am looking to do is setup an association for users and articles (the most basic setup =P). Anyway, I setup the has_many and belongs_to in the models, added the user_id to the article model. Within my create action, I added a variable to save the current_user and then I am able to have that appear within the show page. Problem is I cannot have the username appear within the index page (in my situation, it is called community). Here are the various codes:

Article.rb (Model):

class Article < ActiveRecord::Base
belongs_to :user
...

User.rb (Model):

class User < ActiveRecord::Base
has_many :articles
...

articles_controller:

def create 
@article = Article.create(article_params)
@article.user = current_user
if @article.save
    flash.notice = "Article #{@article.title} has created!"
    redirect_to community_path
  else
    flash.notice = "Try Again!"
  end

end

Show View:

....
<p><%= @article.user.first_name %> <%= @article.user.last_name %></p>
....

Community(Index) View:

<div class="center_com_col col">
<div class="main_community">
<% @articles.each do |x| %>
    <ul>
        <li>
            <h2><%= link_to article_path(x) do %><%= x.title %><% end %><br>
            <p>
                <%= Code to go here for user =><br>
                Written on: <%= x.created_at.strftime("%B %d, %Y") %>
            </p>
            </h2>
        </li>
        <li>
            <p><%= truncate simple_format(x.body), length: 250, escape: false  %> (<%= link_to "read more", article_path(x) %>)</p>
        </li>
    </ul>
<% end %>
</div>

Everything seems to work well but I am clueless when it comes to that community (index) page since I am iterating through the articles.

Thank you very much for any help you may have!

EDIT: Here are my show and community controllers:

def community
  @articles = Article.all.order("created_at DESC").limit(5)
  @users = User.all.order("created_at DESC")
  render :layout => 'community_layout'
end

def show
  @article = Article.friendly.find(params[:id])
  @users = User.all.order("created_at DESC")
  render :layout => 'community_layout'
end

Joe

Upvotes: 0

Views: 351

Answers (1)

Zargold
Zargold

Reputation: 2092

I agree with BroiSatse.

Following some best practices would prevent these errors:

  • Don't use x as the variable name unless referring to x position!

  • Always do if @articles.any? before you begin an each if there are no articles that will cause an error like Nil class Nil!

  • Before you use art.user have an if art.user exists.

Here Should be the code:

<ul> <!--The UL should not be part of your each loop. -->
<% if @articles.any? %>
  <% @articles.each do |art| %>
    <li>
      <h2><%= link_to article_path(art) do %><%= art.title %><% end %><br>
        <p>
    <% if art.user %>
       <%= art.user.first_name %> <%= art.user.last_name %><br>
    <$ end %></h2>
    <%= time_ago_in_words(art.created_at) %>
       </p>
   </li>
   <li>
     <p>
     <%= truncate simple_format(x.body), length: 250, escape: false  %> (<%= link_to "read more", article_path(x) %>)
     </p>
   </li>
<% end %>  <!--end refers to @articles.each -->
</ul> 
 <% end %> 
   <!--end refers to @articles.any? -->

I believe that some of your articles may not have been created with users authoring them ensure that your

db/seeds.rb:

user = User.create(email: "[email protected]", first_name: Faker.first_name, last_name: Faker.last_name)
user.articles.create(title: "ARTICLEs are awesome man!", body: 'Yes in a shocking report people are reading articles")

Also to test specifically do:

rails c

to enter rails console.

articles = Article.all
articles.each { |art| print art.user } => I am guessing you'll get nilClass Nil!

Upvotes: 1

Related Questions