2017-10-27 1 views
0

나는 약간의 필드가있는 객체가있다. name, code 그리고 물론 id이다.SimpleForm을 사용하는 Ruby on Rails : select 또는 : collection_select

다음 코드를 사용하여 내 컨트롤러는 선택한 객체의 id을 수신합니다 (이름은 선택 드롭 다운에 표시되지만).

<%= form.input :department_short, label: I18n.t('department'), wrapper_html: {class: 'header'}, 
          placeholder: 'Select department', as: :collection_select, collection: @departments, required: false %> 

내가 원하는 것은 다른 필드 (또는 더 좋게는이 필드 중 하나 이상을 기반으로 한 것)를 보내는 것입니다. 이것을 할 수있는 방법이 있습니까?

답변

3

는이 같은 람다와 함께 value_method 속성을 사용할 수 있습니다 : 이것처럼

<%= form.input :department_short, label: I18n.t('department'), :value_method => lambda {|t| "#{t.name} - #{t.code}"}, wrapper_html: {class: 'header'}, 
          placeholder: 'Select department', as: :collection_select, collection: @departments, required: false %> 

이 보낸해야한다 "이름 - 코드"값을 사용하면 객체에서, 예제. 람다 작업에서는 원하는대로 객체에서 얻은 값을 조작 할 수 있습니다. 당신이 아이디어를 얻고 이것이 도움이되기를 바랍니다. 행운을 빕니다! 공식 문서 (https://github.com/plataformatec/simple_form)에서

:

편집

Collection inputs accept two other options beside collections: 

label_method => the label method to be applied to the collection to retrieve the label (use this instead of the text_method option in collection_select) 

value_method => the value method to be applied to the collection to retrieve the value 

또한 당신이 당신의 모델에 방법 to_label이있는 경우,이 라벨을 위해 그 방법을 사용하는 것으로 보인다, 당신이 그렇게 돈 label_method를 사용할 때마다 label_method를 넣어야합니다. 의사는 비슷한 to_value 방법이 있는지는 언급하지 않지만 확실히 좋을 것입니다.

+0

정말 감사합니다. 여기에있는 동안 드롭 다운의 표시 이름을 수정하는 비슷한 방법이 있습니까? –

+1

@ap 그래, label_method는 같은 방법으로 작동하므로 라벨을 바꾸기 위해 사용할 수 있습니다. –

+0

당신은 그런 왕자입니다. (이것들이 공식적인 문서에 있다면 좋을 것입니까, 아니면 어딘가에 놓치고 있습니까?) –