Murat Kaya
Murat Kaya

Reputation: 1321

Belongs To User association

I just want to show the username who created the events. But when I try it says

undefined method `user_name' for nil:NilClass

This is my event.rb

class Event < ActiveRecord::Base
  belongs_to :user
  validates :name, presence: true
  validates :description, presence: true, length: {minimum: 5}
end

And this is my user.rb

class User < ActiveRecord::Base
  has_secure_password
  has_many :events
end

And I am trying to show the user name in html.erb file like this.

<%= event.user.user_name %>

But I am getting this error.

So this is my create method in events_controller

def create

    @event = current_user.events.new(event_params)

    respond_to do |format|
      if @event.save
        format.html { redirect_to @event, notice: 'Event was successfully created.' }
      else
        format.html { render :new }
      end
    end
  end

So what should I do for showing username in that page.

Thank You

Upvotes: 3

Views: 965

Answers (2)

Richard Peck
Richard Peck

Reputation: 76784

Although the answer will get your app to work, it won't fix your problem.

The core issue is that your Event doesn't have an associated User object. This would not be a problem, except it seems from your code that you require an Event to have an associated User (current_user.events.new etc)...

You need the following:

#app/models/event.rb
class Event < ActiveRecord::Base
   belongs_to :user 
   validates :user, presence: true #-> always makes sure user exists
   delegate :user_name, to: :user #-> event.user_name
end

--

If you use the above code, you'll be able to call @event.user_name (solving the law of demeter with delegate). You'll also benefit from using validates presence to ensure the :user association exists on create & update.

This will allow you to rely on the @event.user object, which - to me - is far better than having to say "No user associated" in your app:

#view
<%= @event.user_name if @event.user %>

Upvotes: 1

Hoang Phan
Hoang Phan

Reputation: 2166

Ok so here's the problem:

You want to show the event's user's name in index page but you can't be sure all events have one user associated with them. To avoid it you could use.

<%= event.user.try(:user_name) || 'No user associated' %>

Good luck!

Upvotes: 2

Related Questions