只在控制器动作中显示具有相同属性的对象?

时间:2016-06-13 20:17:05

标签: ruby-on-rails ruby routes

<%= link_to categorization_path(categorization: :adventure) do %>    
  <span class="glyphicon glyphicon-picture", id="challenge-category"></span>
<% end %>
# There are other categories such as health, work, wacky, etc

的routes.rb

get ":categorization", to: "pages#home", as: 'categorization'

此时,如果用户点击上面的link_to,我只想显示属性为categorization: adventure的挑战。

我需要在pages#home中放入什么才能使其发挥作用?

pages_controller.rb

def home
 @challenges = current_user.challenges.order("deadline ASC")
 #How to only show one of the :categorization challenges if URL is root_path/:categorization?
end

challenge.rb

CATEGORIZATION = ['adventure', 'health', 'work', 'buy', 'wacky']
scope :adventure,  -> { where(categorizations: 'Adventure') }
scope :health,  -> { where(categorizations: 'health') }
scope :work,  -> { where(categorizations: 'Work') }
scope :buy,  -> { where(categorizations: 'Buy') }
scope :wacky,  -> { where(categorizations: 'Wacky') }
scope :goal,  -> { where(categories: 'Goal') }
scope :habit,  -> { where(categories: 'Habit') }

2 个答案:

答案 0 :(得分:1)

  

如果只显示其中一个:分类挑战,如果URL是   root_path /?:分类

您的默认@challenges已经返回了一个有序的ActiveRecord::Relation对象。因此,您可以将scope链接到它。

class PagesController < ApplicationController
  # 1) using Rails method: `Object#try`
  # http://api.rubyonrails.org/classes/Object.html#method-i-try
  #
  def home
    # default challenges
    @challenges = current_user.challenges.order("deadline ASC")

    if home_params[:categorization]
      # `try` scope categorization param
      # `try` returns nil if param is invalid
      @challenges = @challenges.try(home_params[:categorization])

      # even if no results, empty AR object still returned
      #   => #<ActiveRecord::Relation []>
      #
      unless @challenges.is_a?(ActiveRecord::Relation)
        # do whatever here; remove placeholder on next line:
        raise "invalid categorization => #{home_params[:categorization]}"
      end
    end
  end

  # --OR--

  # 2) using Ruby method: `Object#send`
  # http://ruby-doc.org/core-2.3.1/Object.html#method-i-send
  #
  def home
    # default challenges
    @challenges = current_user.challenges.order("deadline ASC")

    if home_params[:categorization]
      @challenges = @challenges.send(home_params[:categorization])
    end

  rescue NoMethodError
    # do whatever here; remove placeholder on next line:
    raise "invalid categorization => #{home_params[:categorization]}"
  end



  private

  def home_params
    params.permit(:categorization)
  end
end

请参阅:http://guides.rubyonrails.org/active_record_querying.html#scopes
请参阅:http://guides.rubyonrails.org/action_controller_overview.html#strong-parameters

答案 1 :(得分:0)

在你的行动中,尝试用这个替换当前行:

@challenges = current_user.challenges.send(params [:categorization])。order(“deadline ASC”)

应该有效