NoMethodError,has_many和belongs_to关联

时间:2015-07-24 14:15:26

标签: ruby-on-rails ruby ruby-on-rails-4

我收到以下错误。

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>

添加以下内容:

分贝\ 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

请告诉我如何避免此错误。 提前谢谢。

1 个答案:

答案 0 :(得分:1)

问题是你在一组文章上调用了contents方法。

试试这个:

<div class="col-md-6" style="background:yellow;"><%= @user.articles.map(&:contents).join(', ') %></div>