【问题标题】:Correct methods in Ruby on Rails modelRuby on Rails 模型中的正确方法
【发布时间】:2014-06-19 19:04:57
【问题描述】:

我的 Rails 模型有一些不好的线条。一般来说,第一个错误是从has_access def 访问roles 变量时。然后,第二个是在进行where 操作时。

class Organization < ActiveRecord::Base

  has_and_belongs_to_many :organizations_users
  belongs_to :user

  validates :name, :presence => true, :length => { minimum: 4, maximum: 35 }, uniqueness: true
  roles = { :administrator => 1, :support => 2 }

  def has_access(chosen_user, role)
      self.organizations_users.where('user_id = ? and role = ?', chosen_user.id, roles[role]).exists?
  end

  def add_user(chosen_user, role)
      if !self.has_access(chosen_user, role)
          self.organizations_users.create({user_id: chosen_user.id, role: roles[role]})
      end
      has_access(chosen_user,role)
  end

end

我还需要查询organizations_users 表以获取有关访问的信息。我该如何解决?

【问题讨论】:

  • ... 有什么错误?
  • For where 语句 (2nd) 是 #<0x47b0038>&lt;&gt;

标签: ruby-on-rails rails-activerecord has-and-belongs-to-many


【解决方案1】:

最简单的解决办法是改变

def has_access(chosen_user, role)
  where('user_id = ? and role = ?', chosen_user.id, roles[role]).exists?
end

到:

def has_access(chosen_user, role)
  Organization.where('user_id = ? and role = ?', chosen_user.id, roles[role]).exists?
end

原因是 where() 方法是一个类方法,只能从类本身访问,即 IE。 Organization.where。顺便说一句,我假设(危险:))这个 where 子句是从组织中使用的。

【讨论】:

    【解决方案2】:

    要查找或添加组织,请执行以下操作:

    def has_access(role)
      self.organizations_user.find_or_create_by_role(role)
    end
    

    这允许您使用:

    user = User.has_access("administrator")
    
    user = User.first.has_acess("administrator")
    

    如果找不到,则会在表 user_organizations 中查找或创建一个新条目。 ActiveRecord 关系会处理 user_id

    【讨论】:

    • 但是它不能像user_access = User.first.has_access...那样访问
    • 那是因为 User.first 返回单个实例,然后您尝试执行 .where 这是数组的 Class 方法。
    • 然而,这个自我。不行,现在试试。我需要有在类和实例中都可以访问的方法
    • def self.* 生成 Organization.* 类方法。考虑静态编译语言中的静态方法。你不能调用self.*,你必须调用Organization.*
    • 只要有访问权限是布尔值就试试这个。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-14
    • 2015-02-10
    相关资源
    最近更新 更多