0

用戶「立即購買」或「編輯演出」或「下載按鈕」這是代碼我現在有顯示在軌道4

<% if user_signed_in? && @gig.user == current_user %> 
<%= link_to "Edit your gig", edit_gig_path %> 
<% else %> 
    <%= link_to "Get this gig for #{@gig.pointsneeded} points", download_path(@gig)%> 
<% end %> 

第一行說,如果用戶在燒焦和演出由當前用戶顯示擁有「編輯您的演出」, 或者否則如果演出不被用戶所擁有的,顯示他「得到這個演出的點(數字)」

這是該機型的關係,我有

對於Purchase.rb

class Purchase < ActiveRecord::Base 
    belongs_to :gig 
    belongs_to :buyer, class_name: 'User' 
    belongs_to :seller, class_name: 'User' 
end 

對於User.rb

class User < ActiveRecord::Base 
    has_many :purchases, foreign_key: 'buyer_id' 
    has_many :gigs, through: :purchases, source: :buyer 
    has_many :gigs 
    has_many :sales, foreign_key: 'seller_id', class_name: 'Purchase' 
end 

對於Gig.rb

class Gig < ActiveRecord::Base 
    has_many :purchases 
    has_many :buyers, through: :purchases 
    has_many :sellers, through: :purchases 
    belongs_to :user 
end 

問題:如何使邏輯,這樣,如果用戶擁有的演出節目「編輯您的演出」 ELSIF如果用戶從其他用戶購買的演出 和它的在他的current_user.purchases列表中,顯示 「你已經購買了這個演出」,其他「買20分」。

完整的解決方案:

<% if user_signed_in? && @gig.user == current_user %> 
    <%= link_to "Edit your box", edit_gig_path%> 
<% elsif @gig.buyers.pluck(:id).include?(current_user.id) %> 
    <%= link_to "you already purchased this gig", edit_gig_path%> 
<% else %> 
    <%= link_to "Get this box for #{@gig.pointsneeded} points", download_picture_path(@gig)%> 
<% end %> 

回答

1

首先,改變這種做法,@gig不會使SQL調用加載用戶,而是比較演出的USER_ID:

<% if user_signed_in? && @gig.user_id == current_user %> 

比較id而不是實際的對象會使這個頁面更快。

爲了檢查,看看是否CURRENT_USER買了演出,做:

<% if @gig.buyers.pluck(:id).include?(current_user.id) %> 
+0

調用buyer_id當我得到一個未定義的方法「buyer_id」爲'@ gig.user_id'同樣的事情,但這並沒有找到'_id' –

+1

對不起。我更新了我的答案。如果一個演出屬於一個用戶,那麼你應該在你的演出桌上有一個user_id列來修正@ gig.user_id問題。 –

+0

它的工作感謝你。 –