【问题标题】:Rails includes not working with eachRails 包括不使用每个
【发布时间】:2014-10-16 16:02:42
【问题描述】:

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

 <% @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

错误:

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

【问题讨论】:

  • 你能发布你的文章和内容模型吗?
  • 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
  • includes 是 association 的一种方法,正如 diego 在他的回答中所解释的那样

标签: ruby-on-rails view controller include


【解决方案1】:

ActiveRecord includes method is for associations 不是属性。我从您的代码示例中了解到,content 是您的 articles 表中的一个字段,因此,content 不是文章上的关联,而是一个属性,并且在您调用 Article.all 时已经可用。

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

class Article < ActiveRecord::Base
  belongs_to :author # author_id field needs to be present in the articles table
end

然后你可以包含它:Article.includes(:author).all。这将形成 SQL 查询,这些查询将从articles 表及其相关的authors 记录中加载结果。然后在您看来,您可以添加latest.author.name 而不会对数据库产生进一步的查询以分别获取每个相关作者。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多