[英]Rails4: How can I display the name in assosiated table?
What I'd like to do is to display the name in the details table. 我想做的是在详细信息表中显示名称。
I tried some codes, but I couldn't. 我尝试了一些代码,但没有。 Please advise me on how to display the value. 请为我提供有关如何显示值的建议。
Controller code: 控制器代码:
class BooksController < ApplicationController
def show
@book = Book.find(params[:id])
@article = Article.where(book_id: (params[:id])).order(day: :asc)
end
end
View code: 查看代码:
<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>
Relevant model setup: 相关模型设置:
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
Schema: 架构:
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
You want to define an association between Article
and Detail
using the :through
option: 您想使用:through
选项定义Article
和Detail
之间的关联:
class Article < ActiveRecord::Base
belongs_to :book
has_many :details, through: :book
end
You can also define an accessor to find just the detail for the matching day: 您还可以定义访问器以仅找到匹配日期的详细信息:
class Article < ActiveRecord::Base
def matching_detail
details.find_by_day day
end
end
Which you can then use in the view: 然后可以在视图中使用它:
<% @article.each do |a| %>
<%= a.matching_detail.try(:name) %>
<% end %>
It's good to define the associations for articles like 定义诸如以下文章的关联是很好的
has_many :details, through: :book has_many:细节,通过::book
You can also also use this . 您也可以使用this。
Article.includes(:details).where(book_id: (params[:id])).order(day: :asc) Article.includes(:details).where(book_id:(params [:id]))。order(day::asc)
Or 要么
Article.select('articles.name,details.name,..').joins(:details).where([condition]) Article.select('articles.name,details.name,..')。joins(:details).where([condition])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.