【问题标题】:About nested resources with just resources in rails关于只有 Rails 中的资源的嵌套资源
【发布时间】:2018-02-18 04:40:17
【问题描述】:

问题是我希望嵌套资源和普通资源都指向控制器中的相同操作,但根据嵌套资源是否可用而采取不同的行动。

Routes.rb

 resources :users do
     resources :comments  //For having nested routes
 end
 resources :comments  //For having normal routes

嵌套资源

例如

类 CommentsController

 def index
   @user = User.find(params[:id])
   @comment = @user.comments.find(params[:id])
 end

现在,

如果我只想查找所有 cmets,我想使用

/cmets

否则,如果我在用户页面并单击我到达的所有 cmets

/user/:user_id/cmets

因此,如何配置以确保生成正确的页面。

【问题讨论】:

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


    【解决方案1】:

    如果我是你,我会这样做:

    def index
      @comment = Comment.find_by(user_id: params[:user_id], id: params[:id])
    
      # It looked weird that you tried to find a @comment
      # instead of @comments in action `index`
      # I think you made a typing mistake and this can be help
      @comments = Comment.where(user_id: params[:user_id])
    end
    

    【讨论】:

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