mysql - map 表的 Rails 范围

标签 mysql ruby-on-rails scopes

我有以下型号:

class Message < ActiveRecord::Base

  has_many :read_messages

   module Scopes
    def by_read_status(read_status, user_id)
      case read_status
        when 'Unread'

        when 'Read'
          joins(:read_messages).where(:read_messages => {:read => true, :admin_user_id => user_id})
        else
          where('1 = 1') # no scope necessary

      end
    end
  end
  extend Scopes

end

还有...

class ReadMessage < ActiveRecord::Base

  has_many :admin_users
  has_many :messages

end

我有一个名为“mark_as_read”的 Controller 方法来处理该消息。它只是使用该消息 ID 以及标记为已读的人员的管理员用户 ID 创建一个新的 read_message 记录。由于消息是全局的,我希望系统的每个用户都能够单独管理读取状态(这就是为什么我在那里有那个额外的层)。因此,正如您在我的范围中看到的那样, by_read_status('Read', user_id) 将返回找到具有 read true 的映射记录的所有记录。问题是,我该如何做相反的事情呢? (返回未找到映射记录的所有记录,或者映射记录:read 设置为 false)?

我正在使用这样的范围:

@search = Message.search(params[:q])
messages = @search.result.accessible_by(current_ability)
messages = messages.by_company(session[:company_filter]) if session[:company_filter] && session[:company_filter] > 0
messages = messages.by_campaign(session[:campaign_filter]) if session[:campaign_filter] && session[:campaign_filter] > 0
read_filter = params[:read].blank? ? 'Unread' : params[:read]
messages = messages.by_read_status(read_filter, current_admin_user.id)
messages = messages.page(params[:page]).per(20)
@messages = MessageDecorator.new(messages)

所以你可以在我的范围中间看到,我有 by_read_status。如果我返回一个数组或除作用域对象之外的其他内容,它将引发异常。谁能帮我弄清楚如何处理范围的“未读”部分?

谢谢!

编辑答案

exclude = Message.by_read_status('Read', user_id).map(&:id)
exclude = [0] unless exclude.size > 0

where("id not in (?)", exclude)

最佳答案

where("id not in (?)", by_read_status('Read', user_id))

关于mysql - map 表的 Rails 范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19408417/

相关文章:

没有额外权限的Android getServerAuthCode()

php - 如何使用 Cron 和 Codeigniter/PHP 查询 MySQL 数据库?

mysql - 如何在触发器PL/SQL中拆分设置值并插入每一行?

php - 如何使用mysql查询在wordpress页面中显示帖子?

ruby-on-rails - 将 Rails 3.0.9 迁移到 Rails 3.1 时遇到问题? ActiveRecord::连接未建立

ruby-on-rails - Rails - 强制下载 XML 模板而不是呈现

arrays - Julia 中的局部作用域

Mysql - 返回在另一个表中没有关联记录的行加上有记录的最大值

ruby-on-rails - 如何为 Rails 管理员创建自定义 View ?

javascript - 关于范围、node.js 和express 的问题