【问题标题】:Undefined method [model]_url for nested resource嵌套资源的未定义方法 [model]_url
【发布时间】:2014-03-17 03:52:41
【问题描述】:

我正在处理一个嵌套资源项目,并且在我的步骤控制器中出现错误:

  def create
    @step = Step.new(step_params)

    respond_to do |f|
      if @step.save
        f.html { redirect_to @step, notice: 'Step was successfully created.' }
        f.json { render action: 'show', status: :created, location: @step }
      else
        f.html { render action: 'new' }
        f.json { render json: @step.errors, status: :unprocessable_entity }
      end
    end
  end

我得到的错误是:

undefined method `step_url' for #<StepsController:0x007feeb6442198>

我的路线如下所示:

root 'lists#index'

resources :lists do
  resources :steps
end

【问题讨论】:

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


    【解决方案1】:

    当您使用嵌套资源时,请按如下方式更新创建操作:

      def create
        @list = List.find(params[:list_id])
        @step = @list.steps.build(step_params) ## Assuming that list has_many steps
    
        respond_to do |f|
          if @step.save
            ## update the url passed to redirect_to as below
            f.html { redirect_to list_step_url(@list,@step), notice: 'Step was successfully created.' }
            f.json { render action: 'show', status: :created, location: @step }
          else
            f.html { render action: 'new' }
            f.json { render json: @step.errors, status: :unprocessable_entity }
          end
        end
      end
    

    运行rake routes 以查看可用路线。 到steps#show的路线看起来像

    GET lists/:list_id/steps/:id steps#show
    

    使用 list_step_url 和 2 个参数 @list 用于 :list_id 和 @step 用于 :id 以转到显示步骤页面。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-26
      • 1970-01-01
      • 1970-01-01
      • 2016-05-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多