我对 rails 路由的工作方式感到非常困惑。我现在有一个非常简单的应用程序,所以应该很容易调试。这是我的问题 - 我有一个试图调用 show Action 的 Controller ,但它似乎覆盖了我在同一个 Controller 中调用的另一个 Action 。据我从 rake 路由中可以看出,如果 url 读取这个 localhost.com/subscribers/1
应该呈现我想查看的订阅者的 id 但我也有一个 url 像这个 localhost.com/subscribers/visit
那样有效地调用这些页面在工作,在忙?我真的不知道这里发生了什么,所以任何帮助都会很棒!这是我的代码。
Controller
class SubscribersController < ApplicationController
helper_method :sort_column, :sort_direction
def index
@search = Subscriber.search(params[:q])
@subscriber = @search.result
@search.build_condition if @search.conditions.empty?
@search.build_sort if @search.sorts.empty?
end
def show
@subscriber = Subscriber.find_by(id: params[:id])
end
def new
@subscriber = Subscriber.new
end
def create
@subscriber = Subscriber.new(subscriber_params)
if @subscriber.save
@subscriber.touch(:subscription_date)
SubscriberMailer.welcome_subscriber(@subscriber).deliver_now
flash[:notice] = "Subscriber Has Been Successfully Created"
redirect_to new_subscriber_path(:subscriber)
else
render "new"
end
end
def search
@subscriber = Subscriber.new
end
def visit
@subscriber = Subscriber.find_by_phone_number(params[:phone_number])
if @subscriber
@subscriber.visit ||= 0
@subscriber.visit += 1
@subscriber.save
render "visit"
end
end
路线:
devise_for :users
resources :subscribers
resources :comments, only: [:new, :create]
get "subscribers/search", to: "subscribers#search"
get "subscribers/visit", to: "subscribers#visit"
root "subscribers#new"
rake 路线:
subscribers GET /subscribers(.:format) subscribers#index
POST /subscribers(.:format) subscribers#create
new_subscriber GET /subscribers/new(.:format) subscribers#new
edit_subscriber GET /subscribers/:id/edit(.:format) subscribers#edit
subscriber GET /subscribers/:id(.:format) subscribers#show
PATCH /subscribers/:id(.:format) subscribers#update
PUT /subscribers/:id(.:format) subscribers#update
DELETE /subscribers/:id(.:format) subscribers#destroy
comments POST /comments(.:format) comments#create
new_comment GET /comments/new(.:format) comments#new
subscribers_search GET /subscribers/search(.:format) subscribers#search
subscribers_visit GET /subscribers/visit(.:format) subscribers#visit
我在这里做错了什么吗?请帮帮我!
最佳答案
路由器尝试匹配从 routes.rb
顶部到底部的路由,并使用第一个匹配的路由。
在您的情况下, /subscribers/visit
匹配 /subscribers/:id
- 路由器认为这是 ID 为 visit
的订阅者的 show 操作。
如果您将自定义路径移动到路由文件中的 resources :subscribers
上方,您将实现预期的行为。
关于ruby-on-rails - 了解铁路路线,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38175180/