Rails包括不与每个工作

时间:2014-10-16 16:02:42

标签: ruby-on-rails view controller include

我正在尝试在我的控制器中使用includes(刚刚学习了这个概念),但是由于某些原因它在我的索引视图中的每个循环中都没有被rails接受。

 <% @articles.each do |latest|%>
    <div class="row homepage_article text-left">
      <div class="col-md-3">
        <% if latest.photos.present? %>
              <%= image_tag latest.photos.first.image.url(:medium),:class => 'img-    responsive' %>
        <% else %>
          <img src="http://placehold.it/400x300" class="img-responsive">
        <% end %>
      </div>
      <div class="col-md-9">
        <h2 class="title"><%= latest.title %></h2>
        <p class="byline"><%= latest.author %></p>
        <p class="summary"><%= latest.content.split(/\s+/)[0..100].join(' ') %></p>
      </div>
    </div>
    <hr>
  <% end %>

控制器:

  def index

    @articles=Article.includes(:content).all.order(created_at: :desc).paginate(:page => params[:page], :per_page => 3)
    @carousel_article=Article.all.order(created_at: :desc).limit(3)
   #@carousel_article=Article.all.order(created_at: :desc).paginate(:page => params[:page], :per_page => 3)
    @user=current_user
  end

ERROR:

Association named 'content' was not found on Article; perhaps you misspelled it?
Extracted source (around line #39):

     <% @articles.each do |latest|%>
       <div class="row homepage_article text-left">
         <div class="col-md-3">
           <% if latest.photos.present? %>

在这里编辑包括模型。因为你可以看到内容是一个领域。谢谢!

create_table "articles", force: true do |t|
  t.string   "title"
  t.text     "content"
  t.string   "category"
  t.datetime "created_at"
  t.datetime "updated_at"
  t.integer  "user_id"
end

create_table "users", force: true do |t|
  t.string   "first_name"
  t.string   "last_name"
  t.string   "email"
  t.text     "bio"
  t.string   "password"
  t.datetime "created_at"
  t.datetime "updated_at"
  t.string   "avatar_file_name"
  t.string   "avatar_content_type"
  t.integer  "avatar_file_size"
  t.datetime "avatar_updated_at"
end

1 个答案:

答案 0 :(得分:1)

ActiveRecord includes method is for associations无属性。我从您的代码示例中收集contentarticles表中的字段,因此content不是文章的关联,而是属性,并且在您调用{{1}时已经可用}}

现在,如果你的文章模型有一个关联,如作者:

Article.all

然后你可以加入它:class Article < ActiveRecord::Base belongs_to :author # author_id field needs to be present in the articles table end 。这将形成SQL查询,该查询将加载Article.includes(:author).all表及其相关articles记录的结果。然后在您的视图中,您可以添加authors,而不会向数据库发出进一步的查询,以便分别获取每个相关作者。