【问题标题】:Rails routes - context for nested resource urlRails 路由 - 嵌套资源 url 的上下文
【发布时间】:2017-01-31 21:18:23
【问题描述】:

我正在尝试为嵌套资源的显示操作创建嵌套路径

用户.rb

has_many :fan_receives, as: :fanzone_owner, class_name: "FanActivity"

fan_activity.rb

belongs_to :fanzone_owner, polymorphic: true

在我的 routes.rb 中

match ":fanzone_owner_id/posts/:id", to: "fan_activities#show", via: :get

路径有效,但 fanzone_owner_id 可以是任何东西。例如,

example.com/1/fan_activities/2 作品
example.com/2/fan_activities/2 也可以
example.com/anythingatall/fan_activities/2 也可以

我想让 url 的 fanzone_owner_id 必须匹配 fan_activity 的外键,否则我们重定向到 404。

我会在控制器中对 url 进行验证检查吗?我不确定这种方法是否正确

【问题讨论】:

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


    【解决方案1】:

    根据我建议使用nested routes的信息。

    resources :fanzone_owner do
     resources :fan_receive
    end
    

    为此,您还应该准备好nested attributes,否则上述路由将毫无意义。 This tutorial 可能会有所帮助。

    【讨论】:

    • 在我的情况下,事情变得有点复杂,因为 fanzone_owner 被设置为多态,而 fan_receives 实际上是另一个名为“fan_activities”的类,我尝试使用嵌套路由,但它导致了同样的问题.我的目标是让 fan_receives 的 ':show' 路由显示 fanzone_owner 的上下文。
    【解决方案2】:

    我知道出了什么问题。我只需要使用控制器中 url 中的参数进行显示操作。

    在 fan_activities_controller.rb 中

    @user = User.find(params[:fanzone_owner_id])
    @fan_activity = @user.fan_receives.find(params[:id])
    

    如果未找到用户或用户不是 fanzone_owner,则会出现 404。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-05
      • 1970-01-01
      • 2011-05-23
      • 1970-01-01
      • 2011-06-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多