Rails - Use a class method from a another class method with one attribute of the second class

こ雲淡風輕ζ 提交于 2020-01-02 23:01:41

问题


Here is my problem : I have a class method in my User class. I'm calling it from a class method located in my Shop class.

The thing is, the User class method needs the shop's attribute group_id (Group is a third class).

My User class method is not working properly (see Rails 3 Scope - Find users not in a specific group) because it returns nothing although it should return something.

My code currently looks like this :

class User
#...
    # Retrieve all users not in a specific group
    # example: User.not_in_group(Group.find(5))
    def self.not_in_group(groupid)
        includes(:group_users).where("group_users.group_id != ?", groupid)
    end
end

class Shop

  belongs_to :group
  attr_accessible :group_id

  def self.get_users_not_in_shop_group
    User
      .not_in_group(:group_id)
  end

In my logs I get :

...AND (group_users.group_id != 'group_id') ...

I believe I should get something like :

...AND (group_users.group_id != 13) ...

What shall I do ?


回答1:


There are two problems here. First, you got a semicolon before name of group_id variable. Thus, group_id is not parsed as a variable, but as a symbol (for clarity, you can think of it as kind of a string). Second, you should not have get_users_not_in_shop_group as a class-level method as you want to get users not in shop group of some particular shop. You need some object of class Shop to make such a query. Here is what you should do with your Shop class

class Shop
  def get_users_not_in_shop_group
    User.not_in_group(group_id)
  end
end

and here is how your query should like:

Shop.find(4).get_users_not_in_shop_group # I assume this shop has group_id attribute set correctly



回答2:


just like the error message says, group_id is not defined.

Right now, you are defining get_users_not_in_shop_group on self. Which means the function would be called like this: Shop.get_users_not_in_shop_group (on the class, not on a object). Since you are making the call on the class - it has no idea what its group_id is, because its not fetched from the DB.

I think this is what you are looking for:

def get_users_not_in_shop_group
  User.not_in_group(group_id)
end

This way, the function is on the object, not the class. You would call it by doing something like this:

Shop.find(5).get_users_not_in_shop_group


来源:https://stackoverflow.com/questions/24188552/rails-use-a-class-method-from-a-another-class-method-with-one-attribute-of-the

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!