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



我有一个自定义方法的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?

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

resources :groups do
  resources :subscribers
end

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

remove_subscriber完全映射到destroy动作(delete http动词(,但你必须改变id参数 - 会有params[:group_id]params[:id]是订阅者

add_subscribers可能会呈现表单,因此这是new操作

add_subscriber create

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

resources :subscribers

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

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

将上述行添加到routes.rb后,从终端运行rake routes以获得所有路线的体面列表

最新更新