【问题标题】:Scoped resources - missing required keys: [:id]范围资源 - 缺少必需的键:[:id]
【发布时间】:2016-02-09 17:59:17
【问题描述】:

我遇到问题“没有路线匹配 {:action=>"show", :controller=>"picks", :id=>nil} 缺少必需的键:[:id]”

我想要 example.com/staff/picks,所以我在路线中设置了范围。在我创建发布新帖子的表单之前没关系。由于缺少 id,现在无法显示帖子。

routes.db

  resources :places
  resources :events
  root "search#index"
  post 'find' => 'search#find', as: :find


  get '/staff', to: redirect('staff/picks')

  scope 'staff' do
    resources :picks
    resources :discover
  end

picks_controller.rb

class PicksController < ApplicationController
before_action :staff_validate
  def index
    @pickplaces = PickPlaces.all.order('created_at DESC')
  end

  def new
    @pickplaces = PickPlaces.new
  end

  def create
    @pickplaces = PickPlaces.new(pickplaces_params)
    if @pickplaces.save
      redirect_to pick_path
    else
      render 'new'
    end
  end

  def show
    @pickplaces = PickPlaces.find(params[:id])
  end

  def edit
    @pickplaces = PickPlaces.find(params[:id])
  end

  def update
    @pickplaces = PickPlaces.find(params[:id])
    if @pickplaces.update(params[:pickplaces].permit(:title, :about, :location, :kind))
      redirect_to @pickplaces
    else
      render 'edit'
    end
  end

  private

  def pickplaces_params
    params.require(:pickplaces).permit(:title, :about, :location, :kind)
  end
end

staff_controller.rb

class StaffController < ApplicationController
before_action :staff_validate
  def index

  end
end

new.html.slim - 观看次数/选择次数

h1 Add some place that people will love
= form_for :pickplaces, url: picks_path do |f|

  p
    = f.label "Title"
    = f.text_field :title, placeholder: 'Golden Gate'

  p
    = f.label "Location"
    = f.text_field :location, placeholder: 'California, US'

  p
    | Select place type
    = f.radio_button(:kind, "city", :checked => true)
    = f.label(:placetype_city, "City")
    = f.radio_button(:kind, "bridge")
    = f.label(:placetype_bridge, "Bridge")
    = f.radio_button(:kind, "other")
    = f.label(:placetype_other, "Other")

  p
    = f.label "About"
    = f.text_area :about, placeholder: "World's most amazing place"

  = f.submit "Go Public!"

index.html.slim - 观看次数/选择次数

h1 Staff Picks

- @pickplaces.each do |pickplaces|

  h2
    = link_to pickplaces.title, pick_path(@picks)

有点脏

【问题讨论】:

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


    【解决方案1】:

    在您的索引视图中,您使用的实例变量 @picks 尚未在任何地方设置,从而导致路由错误。

    您应该使用集合中的 pickplaces 变量:

    - @pickplaces.each do |pickplaces|
      h2
        = link_to pickplaces.title, pick_path(pickplaces)
    

    【讨论】:

    • 谢谢!就是这样!那么控制器中的重定向呢?当我发布新帖子时,它应该将用户重定向到刚刚创建的帖子//编辑:已解决! redirect_to pick_path(@pickplaces) 我忘了@。再次感谢您!
    猜你喜欢
    • 2015-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多