0

我的应用程序上有一个名为 Source 的应用程序实体。该实体有一个名为 url 的属性。

我想对我的 SHOW 视图进行处理。所以我在显示视图上添加了一个按钮来调用我的控制器并进行此处理。

这是我的路线.rb

  get '/process', to: 'sources#read', as: 'read'

这是我的控制器方法:

class SourcesController < ApplicationController
  before_action :set_source, only: [:show, :edit, :update, :destroy, :read]
  access all: [:index, :show, :new, :edit, :create, :update, :destroy, :read], user: :all
def read
    require 'rss'
    require 'open-uri'
    url = @source.url
    open(url) do |rss|
      feed = RSS::Parser.parse(rss)
      puts "Title: #{feed.channel.title}"
      feed.items.each do |item|
        puts "Item: #{item.title}"
        puts "Link: #{item.link}"
        puts "Description: #{item.description}"
      end
    end
    render template: 'rss_reader/home'
  end

而且当然。我的 show.html.erb:

<%= button_to 'Process Source', read_path(@source), method: :get %>
<%= link_to 'Edit', edit_source_path(@source) %> |
<%= link_to 'Back', sources_path %>
</div>

当我按下“Process Source”按钮时,它会转到正确的控制器方法,但由于以下原因找不到对象@source:

Couldn't find Source with 'id'=
# Use callbacks to share common setup or constraints between actions.
def set_source
  @source = Source.find(params[:id])
end

我在这里做错了什么?

4

1 回答 1

2

您正在访问read_path(@source)预期param 设置id为 value的路由@source.id,但您没有定义路由以支持路径中的任何参数。

我相信read是属于单个实例的动作Source。因此,您应该在 member 上定义路由。这样你就可以params[:id]在你的控制器中访问,并且你的 before_actionset_source可以正常工作。

将您的路线定义更改为:

resources :sources, only: [...] do    # Keep the `only` array just as you have now.
  get '/process', to: 'sources#read', as: 'read', on: :member
end
于 2018-07-18T13:25:22.473 回答