2013-12-18 4 views
9

simple_form보기에 다형성 연관을 표시하는 방법이 있습니까? Simpleform의 다형성 연관

= simple_form_for(@chat, :html => { :class => "form-horizontal" }, :wrapper => "horizontal", defaults: { :input_html => { class: "form-control"}, label_html: { class: "col-lg-4" } }) do |f| 
    = f.error_notification 

    .form-inputs 
     = f.association :from_user 
     = f.association :to_user 
     = f.input :message 
     = f.association :chattable 

    .form-actions 
     = f.button :submit 

그리고 모델 아래

가 :

class Chat < ActiveRecord::Base 
    belongs_to :from_user, :foreign_key => 'from_user_id', class_name: 'User' 
    belongs_to :to_user, :foreign_key => 'to_user_id', class_name: 'User' 
    belongs_to :chattable, polymorphic: true 

    validates :from_user, associated: true, presence: true 
    validates :message, presence: true 
end 

이 오류 아래 밖으로 던져 :

은 지금까지 나는 아래에있어 많은 옷자락, hawing을 통해

uninitialized constant Chat::Chattable 
+0

이것은 포함 문제 일 것 같습니다. Chattable 모델을 보여줄 수 있습니까? – Narfanator

+0

'chattable' 모델이 없습니다. 그것은'polymorphic'이고'chats' 테이블의 일부입니다 –

+0

기다리십시오. 귀하의 모델뿐만 아니라 귀하의 앱이 '채팅'이라고도되어 있습니까? 그것은 당신의 문제 일 수 있습니다. 'Chat' 클래스 이름을 바꾸고'set_table_name' 채팅 이름을 변경하십시오. – Narfanator

답변

5

하고, 앞뒤로, 우리는 SimpleForm이 이것을하지 않는다고 판단했습니다.

여기 이유가 있습니다! (글쎄, 아마도 이유)

SimpleForm은 연관이 어떤 클래스인지 알아 내야합니다. 디폴트 케이스는 연관 이름이 클래스의 de-capitalized 이름이라는 것이기 때문에, 클래스 "Chattable"을 찾는 것을 끝내고 그것을 찾지 못한다. 그것은 에러가 어디서 오는가이다.

좋은 소식은 f.association :chattable 행을 필요한 것을 수행하는 것으로 바꾸는 것입니다. http://guides.rubyonrails.org/form_helpers.html#making-select-boxes-with-ease에는 레일스 양식 도우미와 함께 "쉬운 방법"을 수행하는 데 필요한 정보가 있습니다.

제안 사항은 chattable_type에 대한 선택 상자와 해당 유형의 선택 상자에 대해 HTML 숨김을 해제하는 일부 JS입니다. 그래서 당신은 다음과 같은 것을 얻을 것입니다

= select_tag(:chattable_type, ["Booth", "Venue"]) 

= collection_for_select(:chattable_id, Booth.all) 
= collection_for_select(:chattable_id, Venue.all) 
... 

JS와 CSS는 포함되지 않습니다. 위에 링크 된 문서에서 실제 구문을 확인하십시오. 제 생각에는 제 생각 엔 조금 벗어났습니다.

+0

이 모든 것을 도와 주셔서 감사합니다. !!!! –

+2

괜찮습니다. 문제 해결은 재미있는 일이며, 이제 Rails의 작동 방식에 대해 더 많이 알고 있습니다. – Narfanator

7

JS 조작이 필요하지 않고 간단한 양식 입력을 사용할 수있는 다른 솔루션을 찾았습니다. id가있는 입력 선택 및 옵션 값으로 전달 된 쉼표로 구분 된 입력을 사용할 수 있습니다. 그런 다음 채팅 모델

= f.input :chattable, collection: @chat.chattables, selected: f.object.chattable.try(:signature), 

:

def chattables 
    PolymorphicModel.your_condition.map {|t| [t.name, t.signature] } 
    end 

    def chattable=(attribute) 
    self.chattable_id, self.chattable_type = attribute.split(',') 
    end 

그리고 당신의 PylymorphicModel

def signature 
    [id, type].join(",") 
    end 

당신이 그들을 사용하는 경우 보안 PARAMS에 chattable 추가해야합니다에

.