Rails-如何将控制器中的自定义方法更改为常规方法?

时间:2019-04-17 11:20:25

标签: ruby-on-rails ruby-on-rails-5.2

我有一个Subscribers Controller,其自定义方法如add_subscribersadd_subscriberremove_subscriber

如何将这些方法更改为使用常规的createdestroy方法来执行与自定义方法相同的操作?

app/controllers/subscribers_controller.rb


  def add_subscribers
    @group = Group.find(params[:id])
    authorize @group, :create?

    @course = @group.course    
    @student_subscribers = @course.subscribers
      .where("group_id !=? or group_id is null", @group.id)
  end

  def add_subscriber
    group = Group.find(params[:id])
    authorize group, :create?

    subscriber = Subscriber.find(params[:subscriber_id])
    subscriber.group = group

    if subscriber.save
      flash[:alert] = "Successfully added!"
      redirect_to add_subscribers_group_path(group)
    else
      flash[:error] = "Failed to add user!"
      redirect_to add_subscribers_group_path(group)
    end
  end

  def remove_subscriber
    group = Group.find(params[:id])
    authorize group, :create?

    subscriber = Subscriber.find(params[:subscriber_id])
    subscriber.group = nil

    if subscriber.save
      flash[:alert] = "Successfully removed!"
      redirect_to group
    else
      flash[:error] = "Failed to remove from group!"
      redirect_to group
    end
  end  
end```


I want to use the conventional methods to perform these operations instead of the custom methods. How can I do that?

2 个答案:

答案 0 :(得分:0)

在您的配置/路由文件中:

resources :subscribers

这将为该资源创建标准路由,并将其路由通过订户控制器。现在,您需要在控制器中将方法重命名为createupdate等。

最后,如果您要通过表单点击这些终点,则需要对其进行编辑,以使其指向正确的路线。

将以上行添加到route.rb后,请在终端上运行rake routes,以获取所有路由的详细列表

答案 1 :(得分:0)

从您的代码中可以推断出订阅者是组中的嵌套资源:

resources :groups do
  resources :subscribers
end

这将产生类似/groups/:group_id/subscribers/:id

的路线

remove_subscriber完全映射到destroy动作(delete http动词),但是您必须更改id参数-将有params[:group_id]和{{1 }}是订阅者

params[:id]可能会渲染表单,因此是add_subscribers操作

newadd_subscriber