<%= 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, etcroutes.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?
endchallenge.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') }发布于 2016-07-07 04:14:36
如果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
发布于 2016-06-13 20:26:12
在您的操作中,尝试将当前行替换为以下一行:
@ current_user.challenges.send(params:categorization).order("deadline ASC")
它应该能工作
https://stackoverflow.com/questions/37798418
复制相似问题