2015-09-20 47 views
0

我想要做的是在細節表中顯示名稱。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 

回答

1

您希望使用: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 %> 
+0

感謝您的建議,@eirikir。我試過了,但是出現了下面的NoMethodError。 #'in line'<%= a.matching_detail.try(:name)%>''未定義的方法'matching_detail'。如果你能給我建議,我將不勝感激。 – SamuraiBlue

+0

您是否將我上面定義的'matching_detail'方法添加到您的文章模型中? – eirikir

+0

感謝您的評論,@eirikir。我編輯了錯誤的文件。它在文章模型中編輯後工作。儘管我對這些代碼的見解有限,但我會了解其原因。 – SamuraiBlue

1

很好定義物品的關聯就像

的has_many:詳細信息,通過:書

您也可以也用這個。

Article.includes(:細節)。凡(book_id:(PARAMS [:ID))順序。(天:ASC)

或者

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

+0

感謝您的建議,@rakeshp。我試過has_many。 – SamuraiBlue

相關問題