簡體   English   中英

無法使該IF語句起作用-Rails

[英]Can't get this IF statement to work - Rails

我正在嘗試使其無法顯示頁面,除非資產屬於用戶項目之一(以阻止其他人查看任何內容)。 出於某種原因,我無法使它正常工作,因為它當前正在渲染else部分,而此時應該渲染資產。

    def show
      @website = Asset.find(params[:id])
      ##Add if statement so only current users can view
      if @website.project_id == current_user.projects.all.each { |s| s.id}
        @website
      else
        render(:action => 'blank')
      end


    end

關於我要去哪里的任何想法?

嘗試使用

 def show
   @website = Asset.find(params[:id])

   if current_user.projects.pluck(:id).include?(@website.project_id)
      @website
   else
      render(:action => 'blank')
   end

 end

這比您要實現的目標要優化得多。

錯誤current_user.projects.all.each { |s| s.id} current_user.projects.all.each { |s| s.id}將返回您的一系列項目。 因此,您將永遠無法將project_id與數組進行比較。

相反,您需要一個Project ids數組,然后查找所需的project_id是否包含在該數組中。

編輯

更進一步,我們還可以使用類似

 def show
   @website = Asset.find(params[:id])

   if current_user.projects.find_by_id(@website.project_id).present?          
      @website
   else
      render(:action => 'blank')
   end

 end

這樣,我們期望的結果直接從數據庫中獲取,我們不需要進行太多比較或評估。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM