【问题标题】:Error when removing controller's name from url's从 url 中删除控制器名称时出错
【发布时间】:2015-03-04 07:28:37
【问题描述】:

好的,我有一个 Rails 应用程序,用户可以在其中创建引脚。然后他们可以对这些引脚进行匹配。我要做的是删除 pin url 中的控制器名称。

所以不是:http://localhost:3000/pins/name 我有http://localhost:3000/name

**我通过在我的 **config/routes.rb**** 中使用它来做到这一点

Rails.application.routes.draw do

    resources :pins, :only => [:index, :new, :create], :path => '' do
    resources :comments
    member do
    put 'upvote'
  end 
  end

但是现在,当我尝试评论一个 pin 时,我遇到了这个错误:

wrong constant name 'pin name'

错误来自我的 cmets_controller.rb 的这几行:

  def load_commentable
    resource, id = request.path.split('/')[1, 2]
    @commentable = resource.singularize.classify.constantize.friendly.find(id)
  end

有什么办法可以解决这个问题吗?

编辑:

**rake routes** output:

pin_comments GET      /:pin_id/comments(.:format)            comments#index
                         POST     /:pin_id/comments(.:format)            comments#create
         new_pin_comment GET      /:pin_id/comments/new(.:format)        comments#new
        edit_pin_comment GET      /:pin_id/comments/:id/edit(.:format)   comments#edit
             pin_comment GET      /:pin_id/comments/:id(.:format)        comments#show
                         PATCH    /:pin_id/comments/:id(.:format)        comments#update
                         PUT      /:pin_id/comments/:id(.:format)        comments#update
                         DELETE   /:pin_id/comments/:id(.:format)        comments#destroy

【问题讨论】:

  • 能否提供wrong constant name 'pin name'错误的所有回溯?
  • +rake routes 命令的输出
  • 您需要为此添加自定义路由,但请注意限制有效的引脚名称,否则您将与其他路由发生冲突。

标签: ruby-on-rails ruby pins


【解决方案1】:

使用params(带有请求参数的哈希)而不是resource, id = request.path.split('/')[1, 2]。这应该可以解决您的第二个问题。

【讨论】:

    【解决方案2】:

    我认为你可能来自 php 背景或类似的背景,因为我曾经在我自己使用 php 时这么想,但在 Rails 中你不会触摸 URI 或尝试解析它或任何东西,那是路由器的工作,如果它到达了你代码的那部分,那么工作就已经完成了。

    如果您使用 pin 的名称作为 url,那么您应该使用 friendly_id gem,或者设置模型的 to_param 方法。

    pin 的 id 将始终在 params[:pin_id] 中,因为它在路由中是这样命名的,而评论的 id 将在 params[:id] 中,请注意路由中的变量名称

    /:pin_id/comments/:id
    

    我不确定您所说的资源是什么意思,但如果您指的是模型名称,那么您在引脚的控制器中,因此可以安全地假设它是引脚模型,但如果您想要控制器然后你可以访问params[:controller]

    您的load_commentable 方法在修复所有内容后可能看​​起来像这样

    def load_commentable
      @commentable = Pin.find(params[:pin_id]).comments.where(id: params[:id])
    end
    

    【讨论】:

    • 你是绝对正确的。问题是那些线。我在控制器中进行了更改,所以现在 cmets 捕获了friendly_id gem。谢谢。顺便说一句,如果没有这部分 .cmets.where(id: params[:id]) ,我可以让它工作 - 这对我来说似乎没用,因为正如你所说,rails 可以完成大部分路由过程。
    猜你喜欢
    • 2015-05-06
    • 2013-08-15
    • 1970-01-01
    • 2011-08-04
    • 2015-06-17
    • 1970-01-01
    • 2018-01-10
    • 1970-01-01
    • 2016-11-02
    相关资源
    最近更新 更多