在其父资源视图上显示嵌套资源的错误消息

时间:2014-03-14 03:30:57

标签: ruby-on-rails validation model-view-controller view nested-resources

我有一个嵌套资源(子),只能在其父资源视图中查看和编辑。当调用孩子的行为且孩子无效时,如何在孩子的父母的观点上显示孩子的错误信息?

为了做到这一点,我现在在父母的控制器中有孩子的动作。但是我希望将它放在它所属的孩子控制器中,即我喜欢placements_controller中的activate操作而不是recipients_controller中的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.

1 个答案:

答案 0 :(得分:0)

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

Nested resources主要用于路由结构,但也确保您能够在应用的正确位置容纳正确的数据


<强>代码

#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

如果您希望我们更具体,您将需要提供更多代码:)