2014-02-25 4 views
0

사용자를 만들고 편집하려면 Embedded RubyRails 4을 사용하는 양식 작업을하고 있습니다. 각 사용자는 생성시 역할을 할당 받아야합니다. 처음에는 양식이이 확인란을 사용하여 잘 작동했다. 그러나 라디오 버튼으로 바뀌면 오류가 발생합니다.ERB 라디오 버튼으로 인해 문자열 오류가 발생했습니다.

<%= simple_form_for(@user, html: {class: 'form-horizontal'}) do |f| %> 
<%= f.error_notification %> 

<div class="form-inputs"> 
    <%= f.input :name, autofocus: true %> 
    <%= f.input :email %> 
    <%= f.input :phone_number %> 

    <%= f.input :institution_pid, collection: institutions_for_select, as: :select, label: "Institution" %> 

    <%= f.association :roles, collection: roles_for_select, as: :radio_buttons %> 

    <%= f.input :password %> 
    <%= f.input :password_confirmation %> 

</div> 
<br> 
<div class="form-actions"> 
    <%= button_tag(type: 'submit', class: "btn doc-action-btn btn-success") do %> 
     <i class="glyphicon glyphicon-check"></i> Submit 
    <% end %> 
    <%= link_to @user, {class: "btn doc-action-btn btn-cancel"} do %> 
     <i class="glyphicon glyphicon-remove"></i> Cancel 
    <% end %> 
</div> 

내가 특별히 f.association 비트에 대해 부탁 해요 :

는 형태입니다. 이전에, 내가 사용했을 때

as: :check_boxes 

그것은 정확히 예상대로 작동했습니다. 이제이 오류 메시지가 나타납니다.

NoMethodError in UsersController#update 

undefined method `reject' for "77":String 

"77"은 라디오 버튼 옵션 중 하나의 값입니다.

오류를 던지는 방법은 이것이다 :

def build_role_ids 
    [].tap do |role_ids| 
    roles = Role.find(params[:user][:role_ids].reject &:blank?) 
    roles.each do |role| 
     authorize!(:add_user, role) 
     role_ids << role.id 
    end 
    end 
end 

html로 라디오 버튼을 사용하여 다음과 같습니다

<label class="radio"> 
    <input class="radio_buttons optional" id="user_role_ids_77" name="user[role_ids]" type="radio" value="77"> 
    "Institutional Admin" 
</label> 

확인란 사용 :

<label class="checkbox"> 
    <input class="check_boxes optional" id="user_role_ids_77" name="user[role_ids][]" type="checkbox" value="77"> 
    "Institutional Admin" 
</label> 

I 만약을 누락 된 것이 있거나 더 많은 정보가 필요하면 알려주세요. 고맙습니다!

답변

0

확인란을 사용하면 params[:user][:role_ids]에 반환 된 role_ids의 Array을 가져올 수 있도록 여러 값을 선택할 수 있습니다. 배열에 대해서는 reject 메서드가 구현됩니다. 그러므로, 그것은 그 경우에 효과가있었습니다.

라디오 버튼을 사용하면 한 번에 하나의 값만 선택되므로 role_idsString 값은 params[:user][:role_ids]이됩니다. reject 메서드는 문자열에 대해 구현되지 않습니다. 따라서 오류. 대신

params[:user][:role_ids].reject &:blank? 

role_ids이 비어 있거나없는 경우는 String 객체이기 때문에 당신이 확인할 수의

.

params[:user][:role_ids].empty? 

role_ids가 String 객체가 아닌 배열임을 염두에 build_role_ids 방법 유지를 업데이트합니다.

+0

배열에서 문자열로 변경하는 방법보다 조금 더 편집을해야했지만 일반적인 생각이 효과적이었습니다. 고맙습니다! – user3254621

0

이 오류는 params[:user][:role_ids]Array이 아니라 하나의 String 값임을 나타냅니다. 이것은 체크 박스 (여러 값을 한 번에 선택할 수있는 = Array)에서 라디오 버튼 (한 번에 하나의 값만 선택 가능 = String)으로 변경하기 때문에 의미가 있습니다.

확인란에서 라디오 버튼으로 변경하려면 build_role_ids 메소드 로직을 업데이트해야 값 배열 대신 단일 값을 기대할 수 있습니다.

관련 문제