2017-02-28 23 views
0

我一直在嘗試3年,學習如何使用我的Rails應用程序的專家。Rails 5 - 評論家 - 索引解決範圍方法

我有一個建議模型,我試圖用它來顯示基於我試圖在解析方法中定義的一組規則的提議索引。

我最近的嘗試如下。

class ProposalPolicy < ApplicationPolicy 


    class Scope < Scope 

    def resolve 
         # find all proposals where the user created the proposal; 
     proposal_ids = user.proposal_ids + 
         # all where the user has the reviewing role at the creator's organistion - if the proposal is in scope 'reviewable'; and 
         Proposal.reviewable.for_reviewer(user).pluck(:id) + 
         # all where the proposal is openly published; 
         Proposal.openly_published.pluck(:id) + 
         # all where the user is invited; 
         Proposal.published_to_invitees.invited(user).pluck(:id) + 
         # all where the user is a counterparty and the proposal is published to counterparties 
         Proposal.published_to_counterparties.counterparty(user).pluck(:id) 
     Proposal.where(id: proposal_ids) 
    end 
    end 

在我proposal.rb,我已經定義了我上面的方法使用範圍:

class Proposal < ApplicationRecord 
    scope :reviewable, -> { in_state(:under_review) } 
    scope :openly_published, -> { in_state(:publish_openly) } 
    scope :for_reviewer, -> (user){where(user.has_role?(:consents, @matching_organisation)) } 
    scope :published_to_invitees, -> { in_state(:publish_to_invitees) } 
    scope :invited,  -> (user){ where(invitee_id: user.id) } 
    scope :published_to_counterparties, -> { in_state(:published_to_counterparties_only) } 
    scope :counterparty, -> (user){ where(user_id: @eligible_user)} 
    scope :proponent, ->(user){ where(user_id: user.id) } 

    def matching_organisation 
    @proposal.user.organisation_id == @reviewer.organisation.id 
    end 
end 

當我嘗試這個我沒有得到任何錯誤,但它實際上不工作。如果我創建了一個新提案,那麼我應該能夠在索引中看到該提案,因爲我滿足瞭解決方法中的第一條規則,但是我得到了一個空結果索引。

任何人都可以看到我要去哪裏錯了我試圖寫一個解決方法,可以採取一些標準?

+0

什麼是'@ proposal'在'matching_organization'方法中?這應該是「自我」嗎?這個方法沒有任何爭論 - @ @ proposal和'@ reviewer'從哪裏來? – mysmallidea

回答

0

從代碼示例中可以看出它可能會崩潰,真的很難說。我的建議是爲每個示波器和matching_organization方法建立一個測試場景。

如果還沒有,請爲每個範圍創建一個測試。

describe Proposal do 
    it 'matching_organisation should return the expected organization' 
    assert_equal @expected_org, @proposal.matching_organisation 
    end 
    describe 'scopes' do 
    test 'reviewable' do 
     assert_equal @expected, Proposal.reviewable 
    end 
    test 'for_reviewer' do 
     assert_equal @expected, Proposal.for_reviewer(@user) 
    end 
    # etc... 
    end 
end 

一旦你確定你的類範圍和方法是正確的,你可以創建一個名爲test:

# test/policies/proposal_policy_test.rb 
describe ProposalPolicy do 
    describe 'scope' do 
    it 'must include expected policy' do 
     policy_scope(Proposal).must_include(@expected_policy) 
    end 
    it 'wont include unexpected policy' do 
     policy_scope(Proposal).wont_include(@unexpected_policy) 
    end 
    end 
end 

(圖示例使用MiniTest::Spec語法)