aanfuso
aanfuso

Reputation: 53

Rails association condition with arrays

I'm having a problem with this association.

before:

has_many  :membership, class_name: 'Profile', conditions: "profiles.role != 'owner'"

Currently the attribute "role" isnt an string anymore and now is an array so I need to change that condition that results in records whose "role" is ['owner'] (not 'owner') but I can not us an array to the match.

wanted:

has_many  :memberships, class_name: 'Profile', conditions: "profiles.role != ['owner']"

Profile model

class Profile < ActiveRecord::Base
  attr_accessible :role

  serialize :role, Array
  belongs_to :account

  def roles?(role)
    role.include?(role)
  end
end

Upvotes: 0

Views: 288

Answers (2)

aanfuso
aanfuso

Reputation: 53

I found a solution. The correct query is:

`profiles`.`role` NOT LIKE '%owner%'

Using arel:

Profile.arel_table[:role].does_not_match('%owner%').to_sql

result:

profiles`.`role` NOT LIKE '%owner%

I guess that even with column type "string" serialized, this is still "string" to sql for searching. But, again, is an assumption.

Upvotes: 0

usha
usha

Reputation: 29349

how does role column look in database? is it a string?

If its a varchar column then the below code should work.

has_many  :memberships, class_name: 'Profile', conditions: "profiles.role not in ('owner')"

Upvotes: 1

Related Questions