2012-11-09 43 views
1

我有兩個collection_select字段的表格,第一個是容易的,它只是得到了一個名爲課程模式,這說明課程名稱,當然,返回所選定進程的ID,第二個是我遇到問題的那個,它是課程可能具有的類似課程的collection_select。Rails的collection_select多對多

課程模式:

class Course < ActiveRecord::Base 
    extend FriendlyId 
    friendly_id :name, use: :slugged 
    attr_accessible :code, :credits, :name, :description, :active 

    has_many :similars, dependent: :destroy 
    has_many :similar_courses, through: :similars, source: :similar 

end 

類似的模式:

class Similar < ActiveRecord::Base 
    attr_accessible :course_id, :similar_id 

    belongs_to :course 
    belongs_to :similar, class_name: "Course" 

    validates :similar_id, presence: true 
    validates :course_id, presence: true 

end 

這是同系的模型,這個模型的東西是一門課程必須批准或拒絕,如果一個人想轉移類和類似的東西:

class Homologation < ActiveRecord::Base 
    attr_accessible :homologate_by, :homologate_course, :student_id 
    belongs_to :user 
end 

這是Im有問題的形式:

<%= form_for(@homologation) do |f| %> 
     <%= render 'shared/error_messages', object: @homologation %> 
     <%= f.label :homologate_course %> 
     <%= f.collection_select :homologate_course, Course.find(:all), :id, :name, :prompt => "Select a Course" %> 

     <%= f.label :homologate_by %> 
     <%= f.collection_select :homologate_by, Similar.find(:all), :similar_id, :name, :prompt => "Select a Similar Course" %> 
    <div class="form-actions"> 
     <%= f.submit "Create Homologation", class: "btn btn-large btn-primary" %> 
    </div> 
    <% end %> 
    </div> 

即時得到以下錯誤

http://dpaste.com/hold/827744/

的Bartolleti事情是我希望能夠展示課程的名稱,這當然不是一種方法,但我不知道爲什麼即時得到錯誤,我希望能夠表現出的給出的第一個集合場當然,類似的課程名稱...

謝謝您的幫助!

回答

0

the doc of collection_select

collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {})

然後用你的代碼中有Course.find(Similar.find_by_id(:similar_id)).nametext_method,這就是爲什麼你收到此錯誤信息。

一個解決辦法是增加您的Similar model的方法來獲得類似的課程名稱:

def similar_name 
    similar.name 
end 

那麼您可以在您的collection_select使用它作爲text_method

<%= f.collection_select :homologate_by, Similar.find(:all), :similar_id, :similar_name, :prompt => "Select a Similar Course" %> 
0

這裏的問題是,

 <%= f.collection_select :homologate_by, Similar.find(:all), :similar_id, :name, :prompt => "Select a Similar Course" %> 

      In this line :name is trying to find a record from course and the course name. 

因此,它更好地寫Similar.find(全部)。