vic*_*osa 2 ruby ruby-on-rails-4
我有三个类:用户,订阅和计划.我想加载用户没有的所有计划.在Rails中最好的方法是什么?
我有两个集合:current_user.subscriptions和Plan.where(active: true)
,我使用mongoid
def dashboard
@plans = Plan.where(active: true)#.each { @plans.delete_if has_current_user_plan subscription.title }
end
def has_current_user_plan(name)
current_user.subscriptions.where(title: name, active: true).exists?
end
Run Code Online (Sandbox Code Playgroud)
class User
has_many :subscriptions
Run Code Online (Sandbox Code Playgroud)
class Subscription
belongs_to :plan
belongs_to :user
Run Code Online (Sandbox Code Playgroud)
class Plan
has_many :subscriptions
Run Code Online (Sandbox Code Playgroud)
AR:
class User < ActiveRecord::Base
has_many :subscriptions
has_many :plans, through: :subscriptions # !!!
end
Plan.where(active: true).where.not(id: current_user.plans)
Run Code Online (Sandbox Code Playgroud)
我不确定Mongoid的最佳方法是什么,因为我从未使用它.从我从文档中收集到的内容,虽然我没有运行代码,但以下内容可能会有效.
Plan.where(active: true).not_in(_id: Subscription.where(user_id: current_user.id).pluck(:plan_id))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
72 次 |
| 最近记录: |