Rails: call another controller action from a controller

后端 未结 9 1048
眼角桃花
眼角桃花 2020-11-27 11:47

I need to call the create action in controller A, from controller B.

The reason is that I need to redirect differently when I\'m calling from controller B.

9条回答
  •  萌比男神i
    2020-11-27 12:04

    This is bad practice to call another controller action.

    You should

    1. duplicate this action in your controller B, or
    2. wrap it as a model method, that will be shared to all controllers, or
    3. you can extend this action in controller A.

    My opinion:

    1. First approach is not DRY but it is still better than calling for another action.
    2. Second approach is good and flexible.
    3. Third approach is what I used to do often. So I'll show little example.

      def create
        @my_obj = MyModel.new(params[:my_model])
        if @my_obj.save
          redirect_to params[:redirect_to] || some_default_path
         end
      end
      

    So you can send to this action redirect_to param, which can be any path you want.

提交回复
热议问题