将路由形成错误的操作导致错误

时间:2016-05-24 12:57:15

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

我创建了一个行程网络应用程序,允许用户上传行程并将其他用户行程“下载”到他们的个人资料中。无论出于何种原因而不是我的下载按钮路由到下载控制器,它都会路由到行程控制器并破坏我的应用程序。我似乎无法弄清楚为什么 - 希望你能帮忙。

以下是行程显示页面上的下载按钮:

线路/ show.html.erb

<% if logged_in? %>
  <% unless current_user.downloaded?(@itinerary) %>
    <%= render 'download' %>
  <% end %>
<% else %>
  <p>
  You need to be logged in to download this.
  </p>
<% end %>

部分渲染应该路由到下载控制器:

行程/ _download.html.erb

<%= form_for(current_user.downloadeds.build) do |f| %>
  <div><%= hidden_field_tag :downloaded_id, @itinerary.id %></div>
  <%= f.submit "Download", class: "btn btn-primary" %>
<% end %>

DownloadsController

class DownloadsController < ApplicationController
  before_action :logged_in_user
  def create
    #download id is established in the download form
    @itinerary = Itinerary.find(params[:downloaded_id])
    current_user.download(@itinerary)
    redirect_to @itinerary
  end

而是它路由到行程控制器,这会返回以下错误:

  

ActionController错误 - 缺少参数或值为空:行程

itineraries_controller.erb

  def create
    @itinerary = current_user.itineraries.build(itinerary_params)
    #@user = User.find(params[:id])

    if @itinerary.save
      # render the page with the users itineraries
      flash[:success] = "Your itinerary has been added!"
      redirect_to request.referrer || current_user
    else
      #show the add itinerary page
      flash[:error] = @itinerary.errors.full_messages
      render 'new'
    end
  end

配置/路由

  # You can have the root of your site routed with "root"
  root 'static_pages#home'
  get 'signup' => 'users#new'
  get 'help' => 'static_pages#help'
  get 'about' => 'static_pages#about'
  get 'login' => 'sessions#new'
  post 'login' => 'sessions#create'
  delete 'logout' => 'sessions#destroy'

  resources :users

  resources :itineraries do
    resources :reviews
  end

  resources :downloads, only: [:create, :show]

  mount PdfjsViewer::Rails::Engine => "/pdfjs", as: 'pdfjs'

1 个答案:

答案 0 :(得分:0)

form_for中,没有什么可以告诉它去另一个控制器,所以你必须添加它。你可以提供这种选择:

<%= form_for(current_user.downloadeds.build, url: {controller: downloads}) do |f| %>

这应该更改将发送下载的控制器。您可以提供哈希参数(例如url: { controller: 'controller_name', action: 'action_name' }),路由助手(例如url: download_path(@download))或显式网址(例如url: "http://example.com")。您选择的格式取决于您的需求和偏好。