has_manyハックとハックbelongs_toユーザーのユーザーモデルがあります。ハックにはフィールドuser_idがあります。
ホームアクションを持つstatic_pages_controllerがあります:
def home
@hacks = Hack.all
@users = User.all
end
ユーザーモデルは次のとおりです。
class User < ActiveRecord::Base
attr_accessible :username, :email, :password, :password_confirmation
has_secure_password
has_many :hacks
end
ハックモデルは次のとおりです。
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
ビューで、ハックをループして、それに関連付けられているユーザーを特定します。
<% @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 %>
次のエラーが発生します。
undefined method `username' for #<Enumerator:0x007fd5078ac7b0>
私がここで間違っていることについての考え。参考:ユーザー名は、ユーザーモデルからアクセス可能なフィールドです。