0
分別檢索內容爲每個協會

我的系統有以下關聯設置:的Rails 3:通過AJAX

class Book < ActiveRecord::Base 
has_many : suggestions 
has_many : comments 
has_many : references 

顯示鑑於我的書的模式,我想給用戶一個選項來選擇(從下拉框中)他們希望看到的視圖。因此,例如,如果用戶選擇從該下拉框建議然後與建議的部分重新加載。對於其他3個選項也是如此。 爲了實現這一點,我寫在我的模型下面的方法,book.rb

def self.select_content_type(content_type) 
case content_type 

when "suggestions" 
    # get the suggestions 
    @book_suggestions = Book.suggestions.paginate(:per_page => 6, :page => params[:page]) 
    # return this 
    return @book_suggestions 

when "comments" 
    # get the comments 
    @book_comments = Book.comments.paginate(:per_page => 6, :page => params[:page]) 
    # return this 
    return @book_comments 

when "references" 
    # get the references 
    @book_references = Book.references.paginate(:per_page => 6, :page => params[:page]) 
    # return this 
    return @book_references 

我想在「顯示訪問此方法「我book_controller.rb的作用如下:

@book_content = Book.select_content_type(params[:content_type]) 

顯示觀,我有以下形式進行GET請求此方法:

- form_tag book_path(@book), :id=>"select_rel_form", :remote => true, :method => 'get' do    
     = text_field_tag :content_type, params[:content_type], :id=>"select_rel_type" 
     = submit_tag "submit", :name => nil, :class=>"select_rel_submit" 

而且在部分名爲* _content *我訪問返回的值如下:

- if [email protected]_content.nil? 
    - @issue_relations.each do |relation| 
    ... 

我得到出現以下錯誤:

NoMethodError (undefined method `suggestions' for #<Class:0x1177f4b8>): 
app/models/book.rb:93:in `select_content_type' 
app/controllers/books_controller.rb:21:in `show' 

請幫助我瞭解如何解決此問題。如果有一個正確和更好的方法來實現這一點,請指導我。謝謝。

+0

您book.rb方法self.select_content_type不會有任何效果。你在模型中引用params [:page],但你沒有那個變量。 PARAMS在控制器中,我看不到你將它傳遞給模型的位置。 – redronin 2012-01-28 04:54:55

+0

@redronin,我使用will_paginate進行分頁(一次顯示6)的內容。 params [:page]是一個will_paginate參數。 – rgoraya 2012-01-28 22:32:54

回答

0

您的表單標籤具有SELECT_CONTENT_TYPE和它說,這是不確定的,但你應該有類似book_path(@book)

+0

感謝您的回答。現在該表單似乎根據需要訪問模型方法。但是我收到另一個錯誤(更新了問題)。不知何故,.suggestions關聯沒有被正確識別。 – rgoraya 2012-01-28 04:26:27

+0

它不承認,因爲你有'Book.comments',你應該有類似'@book = Book.find(PARAMS [:編號])'然後'@book_comments = @ book.comments.paginate(:per_page => 6,:頁面=> PARAMS [:頁面])' – 2012-01-29 12:53:44

+0

感謝您的回答幫我找到這個問題。 – rgoraya 2012-01-31 00:29:27

0

不是一個答案,但你的self.select_content_type方法可能是多機:

def self.select_content_type(content_type) 
    return unless ['suggestions', 'comments', 'references'].include?(content_type) 
    Book.send(content_type.to_sym).paginate(:per_page => 6, :page => params[:page]) 
end 

此外,您使用PARAMS [:頁面],但你永遠不會PARAMS傳遞。你應該把這個方法留在控制器中,不知道爲什麼它需要在模型中。

+0

@redorin,你建議我做它的控制方法,並指定我*的routes.rb *文件路徑?你能指導我爲什麼在這種情況下會更好嗎? – rgoraya 2012-01-28 22:37:19