繁体   English   中英

Rails4:如何在关联表中显示名称?

[英]Rails4: How can I display the name in assosiated table?

我想做的是在详细信息表中显示名称。

我尝试了一些代码,但没有。 请为我提供有关如何显示值的建议。

控制器代码:

class BooksController < ApplicationController
  def show
    @book = Book.find(params[:id])
    @article = Article.where(book_id: (params[:id])).order(day: :asc)
  end
end

查看代码:

<div class="row">
  <% @article.each do |a| %>
    <%= a.day %><br>
    <%= a.title %><br>
    # want to display the name in detail table where (details.day = articles.day and details.book_id = articles.book_id)
  <% end %>
</div>

相关模型设置:

class Article < ActiveRecord::Base
    belongs_to :Book
    default_scope -> { order(day: :asc, start_time: :asc) }
end

class Detail < ActiveRecord::Base
    belongs_to :Book
end

class Book < ActiveRecord::Base
    has_many :articles
    has_many :details
end

架构:

ActiveRecord::Schema.define(version: 2015099999999) do

  create_table "details", force: true do |t|
    t.integer  "book_id"
    t.integer  "day"
    t.string   "name"
    t.string   "detail"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "articles", force: true do |t|
    t.integer  "book_id"
    t.integer  "day"
    t.string   "start_time"
    t.string   "end_time"
    t.integer  "category"
    t.string   "title"
    t.string   "contents"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "books", force: true do |t|
    t.date     "publish_date"
    t.string   "title"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

end

您想使用:through选项定义ArticleDetail之间的关联:

class Article < ActiveRecord::Base
  belongs_to :book
  has_many :details, through: :book
end

您还可以定义访问器以仅找到匹配日期的详细信息:

class Article < ActiveRecord::Base
  def matching_detail
    details.find_by_day day
  end
end

然后可以在视图中使用它:

<% @article.each do |a| %>
  <%= a.matching_detail.try(:name) %>
<% end %>

定义诸如以下文章的关联是很好的

has_many:细节,通过::book

您也可以使用this。

Article.includes(:details).where(book_id:(params [:id]))。order(day::asc)

要么

Article.select('articles.name,details.name,..')。joins(:details).where([condition])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM