我想要做的是在細節表中顯示名稱。Rails4:我如何在關聯表中顯示名稱?
我嘗試了一些代碼,但我不能。 請告訴我如何顯示值。
控制器代碼:
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
感謝您的建議,@eirikir。我試過了,但是出現了下面的NoMethodError。 #'in line'<%= a.matching_detail.try(:name)%>''未定義的方法'matching_detail'。如果你能給我建議,我將不勝感激。 –
SamuraiBlue
您是否將我上面定義的'matching_detail'方法添加到您的文章模型中? – eirikir
感謝您的評論,@eirikir。我編輯了錯誤的文件。它在文章模型中編輯後工作。儘管我對這些代碼的見解有限,但我會了解其原因。 – SamuraiBlue