我想要做的是在详细信息表格中显示名称。
我尝试了一些代码,但我做不到。 请告诉我如何显示价值。
控制器代码:
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
答案 0 :(得分:1)
您想使用Article
选项定义Detail
和:through
之间的关联:
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 %>
答案 1 :(得分:1)
定义
等文章的关联是件好事has_many:详情,通过:: book
你也可以使用它。
Article.includes(:details).where(book_id:(params [:id]))。order(day :: asc)
或者
。Article.select(&#39; articles.name,details.name,..&#39)连接(:细节)。凡([条件])