Search code examples
ruby-on-railsactiverecordhas-and-belongs-to-many

How to setup has_and_belongs_to_many relationship with a scoped and aliased class?


I try to associate Roles to a Group (of users). The Role class does not exist, I use an extract (a scope) of the Parameter class. I got inspiration from apidock.com, but cannot implement the example using a scope. I setup the relationship as follow:

##group.rb
  has_and_belongs_to_many :roles, :class_name => "Parameter", -> { where("parameters_list_id = ?", 13) }

##paramter.rb
  has_and_belongs_to_many :groups

When I add the lambda for scoping the relation, the following error raises:

group.rb:39: syntax error, unexpected '\n', expecting =>

Can you help me to solve this issue?

Thank you for your help.


Solution

  • Changed the order of parameters and indented for clarity:

    has_and_belongs_to_many :roles,
                            -> { where("parameters_list_id = ?", 13) },
                            :class_name => "Parameter"
    

    Options always come in the end of the parameter list. Hashes sometimes can come in the middle, but then they have to be delimited by {}. The brackets can only be omitted if the hash is the last parameter.