ruby-on-rails - 在父视图的资源上显示嵌套资源的错误消息

  显示原文与译文双语对照的内容
124 2

我有一个嵌套资源( 子级),只在它的父视图的资源上查看和编辑。如何在调用子对象的操作和子对象无效时对它的父显示器的视图进行错误消息。

为了做到这一点,我现在在父级的控制器中有孩子的动作。如果我想把它放在孩子的控制器里,我想在 换句话说,中的activate 操作而不是在中的activate_placement 动作。

routes.rb:

# Present setup:
patch '/recipients/:recipient_id/placements/:id/activate' =>
 'recipients#activate_placement', :as => :activate_recipient_placement
# Placement is activated (and validated) by recipients_controller.
# If errors exist, recipient's show view with that placement is rendered 
# displaying the placement's error messages. I want that. 
# But I'd like the activate action to be in the placements_controller.
# Preferred setup:
resources :recipients do
. . .
 resources :placements do
 patch 'activate' on: :member
 end
end
# Now, placement is activated (and validated) by placements_controller.
# But if errors exist on the placement, the placement's own show view,
# rather than the parent's show view, is rendered with the error messages.
时间:原作者:

127 3

设置应该在他们自己的控制器中

嵌套资源主要用于路由结构,但也确保你能够在应用程序的适当位置容纳正确的数据。


代码

#config/routes.rb
resources :recipients do 
 resources :placements #->/recipients/5/placements/new
end
#app/controllers/placements_controller.rb
def new
 @placement = Placement.new
end
def create
 @placement = Placement.new(placement_params)
 @placement.save
end 
private
def placement_params
 params.require(:placement).permit(:info, :about, :placement).merge(recipient_id: params[:recipient_id])
end

如果你希望我们更具体,你必须提供更多的代码:)

原作者:
...