【问题标题】:How do I call my "show" method without any parameters?如何在没有任何参数的情况下调用我的“显示”方法?
【发布时间】:2018-01-20 18:41:03
【问题描述】:

我的 routes.rb 文件中有这个

resources :votes

当我运行 rake 路线时,它给出了

   votes GET    /votes(.:format)                   votes#index
         POST   /votes(.:format)                   votes#create
new_vote GET    /votes/new(.:format)               votes#new

edit_vote GET /votes/:id/edit(.:format) votes#edit 投票 GET /votes/:id(.:format) votes#show

我的问题是如何在没有任何参数的情况下调用我的“/show”方法?如果有人不提供 ID,我想使用此控制器方法生成随机结果

  def show
    id = params[:id]
    # If there is no person selected based on the param, choose one randomly
    if !id.present?
      if current_user
        @person = Person.joins("LEFT JOIN users ON users.id = people.user_id")
                        .where("people.user_id IS NULL")
                        .order("RANDOM()").limit(1).first
      end
      if @person.nil?
        @person = Person.order("RANDOM()").limit(1).first
      end
    else
      @person = Person.find_by_id(id)
      if current_user
        @vote = Vote.where(person_id: id, user_id: current_user.id).first || Vote.new
      end
    end
  end

但是现在当我在浏览器中输入“/votes”时,它会因错误而死

The action 'index' could not be found for VotesController

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-5 rails-routing


    【解决方案1】:

    至少当您使用resources 时,您不能——resources 生成一组符合 RESTful 实践的标准路由。在您的情况下,它正在生成 get '/votes/:id', to: 'votes#show'

    因为没有匹配的参数,它假设你正在尝试去votes#index

    如果你想同时匹配两者,我会在你的routes.rb 中做这样的事情:get '/votes(/:id)', to: 'votes#show' 括号表示可选参数。您可能需要将其放在 resources 块之前,或更改您的 resources 块以省略 show 操作。

    更多参数:http://guides.rubyonrails.org/v5.1.1/routing.html#bound-parameters

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-27
      • 1970-01-01
      • 2019-10-24
      • 2011-05-01
      相关资源
      最近更新 更多