【问题标题】:Rails - what's the correct path for inner controllers?Rails - 内部控制器的正确路径是什么?
【发布时间】:2013-08-08 11:30:18
【问题描述】:

我在 routes.rb 中有这个设置:

resources :users do
  resources :images do
    resources :comments
  end
end

当我从 ImagesController 加载 show 动作时,模板文件中的内容如下:

...
= render 'comments/form', :@comment => @image.comments.new
...

cmets/form 文件如下:

= form_for [@comment.commentable, @comment] do |f|
  .field
    = f.text_field :body
  .actions
    = f.submit 'Comment'

还有 show 动作:

def show
    @user = User.find(params[:user_id])
    @image = @user.images.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.json { render :json => @image }
    end
  end

但是当我在浏览器中加载这个页面时,我得到了这个错误:

undefined method `image_comments_path' for #<#<Class:0x007feb48488128>:0x007feb48399668>

为什么 Rails 返回此错误消息?

【问题讨论】:

    标签: ruby-on-rails ruby path controller routes


    【解决方案1】:

    打开您的终端并输入 rake routes 以查看您的应用中可用的正确路线

    【讨论】:

      【解决方案2】:

      在你的 show 方法中,

      def show
        @user = User.find(params[:user_id])
        @image = @user.images.find(params[:id])
      
        ## Add this line:
        @comment = @image.comments.build 
      
        respond_to do |format|
          format.html # show.html.erb
          format.json { render :json => @image }
        end
      end
      

      在你的模板中,如果你正在渲染一个模板,

      = render "comments/form", :locals => { :comment => @comment } %>
      

      在你的comments/form 中这样写:

      = form_for comment do |f|
       .field
         = f.text_field :body
       .actions
         = f.submit 'Comment'
      

      它应该工作。谢谢

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-01-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多