![](/img/trans.png)
[英]belongs_to / has_many association throwing NoMethodError: undefined method
[英]NoMethodError, has_many and belongs_to association
我收到以下错误。
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
\\用户\\ 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>
添加了以下内容:
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
请告诉我如何避免此错误。 先感谢您。
问题是您要在文章集合上调用contents
方法。
尝试这个:
<div class="col-md-6" style="background:yellow;"><%= @user.articles.map(&:contents).join(', ') %></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.