Active Record Query选择一个尚未进行投票的条目

时间:2015-05-22 11:18:08

标签: ruby-on-rails activerecord ruby-on-rails-4.2 ruby-2.2

我有以下三个模型

Judge(设计用户)

Judge.column_names
=> ["id", "email", "encrypted_password", "reset_password_token", "reset_password_sent_at", "remember_created_at", "sign_in_count", "current_sign_in_at", "last_sign_in_at", "current_sign_in_ip", "last_sign_in_ip", "created_at", "updated_at", "confirmation_token", "confirmed_at", "confirmation_sent_at", "unconfirmed_email"]

class Judge < ActiveRecord::Base
   has_many :votes
end

条目

Entry.column_names
 => ["id", "entrant_id", "title_of_work", "price", "created_at", "updated_at", "media_file_name", "media_content_type", "media_file_size", "media_updated_at", "paid", "height", "width", "type_of_media"]

class Entry < ActiveRecord::Base
    belongs_to :entrant
    has_many :votes
end

投票

Vote.column_names
=> ["id", "entry_id", "judge_id", "score", "created_at", "updated_at"]

class Vote < ActiveRecord::Base
    belongs_to :entry
    belongs_to :judge
end

我需要一个执行以下操作的查询

如果我以法官的身份登录,请选择一个已付款的入场券,但我还没有投票。

我有这个,但它似乎不起作用

Entry.where(:paid => 1).includes(:votes).where.not(votes: { id: nil }).where.not(votes: {judge_id: current_judge.id }).first

我正在尝试创建一个显示可以投票的“条目”的页面。一旦投票,投票表中将有一条记录,它将永远不会再次显示。有许多法官,因此这些规则中的每一条都适用于每位法官。

有更好的方法吗?

2 个答案:

答案 0 :(得分:1)

这可以解决您的问题

Entry.includes(:votes).where(paid: 1).where("votes.judge_id != ? ", current_judge.id)

答案 1 :(得分:0)

如果您的意思是说您有判断力,并希望获取已付款且未获得任何投票的参赛作品?然后,以下查询可能会对您有所帮助: //get fieldset object via the FormElementManager ServiceManager $employeeAccountFieldset=$this->getServiceLocator()->get('FormElementManager')->get('MyNameSpace\Form\Fieldset\EmployeeAccount'); //remove password element $employeeAccountFieldset->remove('password'); //tweak an element $employeeAccountFieldset->get('email')->setAttribute('class','myCSSClass'); //add tweaked fieldset to form $myFormObject->add($employeeAccountFieldset);