2

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!

1 Answer 1

4

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

attr_accessor :member_selection
1
  • As always, it's something simple. Everything works as expected now. Thanks!
    – Merovian
    Sep 26, 2013 at 13:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.