Domanda

I am having a heck of a time figuring out how to get a virtual attribute past CanCan during a new record create:

I have Teams, with :name and :description

Teams have users through memberships, which I control through a separate controller action, and which holds data in a param I call "member_selections", containing a hash with non-specific keys (user_id => role).

Thus: My params hash might look like this:

params[:team] = {name: "Super Team", description: "It is super", 
member_selections: {"1"=>"member", "2"=>"leader"}}

I have the usual CanCan solution to strong params as referenced here: https://github.com/ryanb/cancan/issues/835

To punch the virtual attribute through the whitelist, I used a technique mentioned here, at the bottom: http://blog.sensible.io/2013/08/17/strong-parameters-by-example.html

Specifically my "team_params" method looks like this:

def team_params
  params.require(:team).permit(:name, :description).tap do |whitelist|
    whitelist[:member_selection] = params[:team][:member_selection]
  end
end

Now, if I remove the .tap and whitelist block, I can create new teams, but cannot add new members.

If I maintain the .tap I can add new members, but I cannot create new teams. A submit of the 'new' form gives a result of:

ActiveRecord::UnknownAttributeError in TeamsController#create
unknown attribute: member_selection 

It gives this error even before the TeamsController#create method is properly called, so it's not an issue of my passing the parameters incorrectly to Team.new/.create, and suggests that it's a CanCan issue.

Does anyone else have this trouble with virtual attributes and CanCan in Rails 4? How can I get around this?

Thanks!

È stato utile?

Soluzione

I think you need to add an attr_accessor to your Team model

attr_accessor :member_selection
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top