Reputation: 861
I receive the following error.
NoMethodError in Users#show
...
undefined method 'contents' for # <Article::ActiveRecord_Associations_CollectionProxy:0x43745a0>
...
<div class="col-md-6" style="background:yellow;"><%= @User.articles.contents %></div>
user.rb
class User < ActiveRecord::Base
has_many :articles
end
article.rb
class Article < ActiveRecord::Base
belongs_to :user
end
users_controller.rb
class UsersController < ApplicationController
def index
...
end
def show
@user = User.find(params[:id])
...
end
end
\users\show.html.erb
<div class="row">
<div class="col-md-12" style="background:orange;"><%= @user.title %></div>
</div>
<div class="row">
<div class="col-md-6" style="background:blue;"><%= @user.articles.count %></div>
<div class="col-md-6" style="background:yellow;"><%= @user.articles.contents %></div>
</div>
added followings:
db\schema.rb
ActiveRecord::Schema.define(version: 20150720033506) do
create_table "articles", force: true do |t|
t.integer "user_id"
t.integer "day"
...
t.string "title"
t.string "contents"
...
end
create_table "users", force: true do |t|
t.date "user_date"
t.string "title"
t.datetime "created_at"
t.datetime "updated_at"
end
Please advise me on how to avoid this error. Thank you in advance.
Upvotes: 1
Views: 98
Reputation: 4005
The problem is that you are calling the contents
method on a collection of articles.
Try this:
<div class="col-md-6" style="background:yellow;"><%= @user.articles.map(&:contents).join(', ') %></div>
Upvotes: 1