2013-07-26 26 views
12

Tôi có điều này trong quan điểm của tôi đó là một hộp kiểm multiselectthông số mạnh mẽ không chấp nhận mảng

Mẫu

class User < ActiveRecord::Base 
    has_many :user_roles, :dependent => :destroy 
    accepts_nested_attributes_for :user_roles, :allow_destroy => true 
    has_many :roles, :through => :user_roles 
end 

xem

<%= check_box_tag 'user[role_ids][]', role.id, user.blank? ? nil : user.roles.include?(role) ,id: dom_id(role)%> 

các thông số mạnh mẽ cho điều này là được viết là

def user 
    params.require(:user).permit(:first_name,{:role_ids => []}) 
    end 

Nhưng trên tạo ra nó nói

Processing by Admin::UsersController#create as HTML 
    Parameters: {"utf8"=>"✓", "authenticity_token"=>"+y8iWya5KIILqS0embEUEZuClycXq0O9Q4pA+MnbM0g=", "user"=>{"first_name"=>"", "last_name"=>"", "email"=>"[email protected]", "language"=>"en", "access_level_id"=>"1", "role_ids"=>["", "1", "", "5", "", "", ""], "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Create user"} 

Unpermitted parameters: role_ids 
Unpermitted parameters: role_ids 
Unpermitted parameters: role_ids 
Unpermitted parameters: role_ids 

Bất kỳ manh mối tại sao nó không chấp nhận các mảng role_ids mà là đến từ hình thức?

Trả lời

7

trả lời bản thân mình, tôi đã nhận nó làm việc không trực tiếp, nhưng phương pháp dưới đây từ Strong Parameters issues discussion giúp tôi trong việc chuyển đổi một tham số bình thường thành một danh sách trắng.

def user_params 
    params.require(:user).permit(:first_name).tap do |whitelisted| 
    whitelisted[:role_ids] = params[:user][:role_ids] 
    end 
end 
8

này nên làm việc

params.require(:user).permit(:first_name, :role_ids => []) 
+1

tốt tôi đã cố gắng theo cách này quá .. nó đã không làm việc .. – AnkitG

+0

dán phương pháp tạo của bạn pls – Benj

+0

tạo GIST [ở đây] (https://gist.github.com/ankit8898/6088035). Vui lòng xem – AnkitG

21

Xem Rails Strong Parameters documentation regarding nested attributes.

Định dạng đúng là:

params.permit(:name, {:roles => []}, ...) 

AnkitG's solution làm việc cho tôi trong Rails 4 sử dụng Role Model đá quý cho mô hình của tôi sử dụng. thực hiện điều khiển người dùng của tôi về _params kết thúc lên trông như:

def user_params 
    # Bug with permit for nested arrays... @see https://stackoverflow.com/a/17880288/2631472 
    params.require(:user).permit(:first_name, :last_name, :middle_name).tap do |whitelisted| 
    whitelisted[:roles] = params[:user][:roles] 
    end 
end 

+0

Làm việc cho tôi. Cảm ơn! –