0
votes

I have a user model that has_many hacks and hack belongs_to user. Hack has a field user_id.

I have a static_pages_controller with a home action:

def home
  @hacks = Hack.all
  @users = User.all
end

The user model is:

class User < ActiveRecord::Base
  attr_accessible :username, :email, :password, :password_confirmation
  has_secure_password

  has_many :hacks
end

The hack model is:

class Hack < ActiveRecord::Base
  attr_accessible :hack_name, :serial_ids, :commentary

  has_many :hacktions, :dependent => :destroy
  has_many :serials, through: :hacktions
  belongs_to :user

  default_scope order: 'hacks.created_at DESC'

  extend FriendlyId
  friendly_id :hack_name, use: :slugged
end

In the view I want to loop through the hacks and then identify the user that is associated with it:

<% @hacks.each do |h| %>
  <span><%= @users.find(h.user_id).username %>
  <div class = "home-date"><%=  h.created_at.strftime("%B %m, %Y - %I:%M %p")  %><%=   image_tag("housing.png") %></div>
  <div class = "home-title"><%= link_to h.hack_name, hack_path(h) %></div>
  <div class = "commentary lead"><%= markdown(h.commentary) %></div>
<% end %>

I'm getting the following error:

 undefined method `username' for #<Enumerator:0x007fd5078ac7b0> 

Any ideas what I'm doing wrong here. FYI: username is an accessible field from the user model.

2
show your models and relationssanny Sin
Thanks sanny Sin, alestanis rightfully discovered that I needed to put first before the call to username.JohnGalt
@sanny Sin I've updated my models in the post.JohnGalt

2 Answers

1
votes

Try calling first on the results of your find:

@user.find(h.serial_id).first.username
0
votes

Try changing:

<span><%= @user.find(h.serial_id).username %>

to

<span><%= @user.find_by_serial_id(h.serial_id).username %>