0

Apologies for posting what seems to be an oft-asked question but I have toiled for two days without getting closer.

I am running Rails 4.0.1 (with Devise, CanCan, among others) and have user and role models with a HABTM users_roles table (as created by the since-removed rolify).

class Role < ActiveRecord::Base

  has_and_belongs_to_many :users, :join_table => :users_roles
  belongs_to :resource, :polymorphic => true

  attr_reader :user_tokens

  def user_tokens=(ids)
    self.user_ids = ids.split(",")
  end
end

My submitted form data is:

"role"=>{"name"=>"disabled", "resource_id"=>"", "resource_type"=>"Phone", "user_tokens"=>["", "3"]}

(Not sure where the empty string comes from; it's not in the option list, but hey, welcome to Rails).

My problem is with getting the user_tokens data passed into the appropriate variable in the controller.

There are lots of postings suggesting the correct format (e.g., how to permit an array with strong parameters)

If I specify the permitted parameters thus:

params.require(:role).permit(:name, :resource_id, :resource_type, :user_tokens => [] )

I get a '500 Internal server error' with no other details.

If I specify the permit as

params.require(:role).permit(:name, :resource_id, :resource_type, user_tokens: [] )

I don't get any errors (No unpermitted parameters in the dev log) but the user_tokens array is not passed through in the @role.

If I run this scenario through a console I get:

params = ActionController::Parameters.new(:role => {:resource_id => "", :resource_type => "Phone", :user_tokens => ["", "3"]})
params.require(:role).permit(:name, :resource_id, :resource_type, user_tokens: [] )
=> {"resource_id"=>"", "resource_type"=>"Phone", "user_tokens"=>["", "3"]}
params.require(:role).permit(:user_tokens).permitted?
Unpermitted parameters: resource_id, resource_type, user_tokens
=> true

I'm stuck as to where I should try looking next.

Community
  • 1
  • 1
RubyNewby
  • 11
  • 2

1 Answers1

0

Even though I was sure I had already tried it, changing the model to be

  def user_tokens=(ids)
    self.user_ids = ids
  end

fixed it. I've always struggled to understand this bit of notation except when I've spent 4 days trying why my many:many models don't work. I guess it'd be easier if I was doing this full time rather than just for particular sysadmin projects.

RubyNewby
  • 11
  • 2