我有一个自定义方法的Subscribers Controller
,如add_subscribers
,add_subscriber
和remove_subscriber
。
如何将这些方法更改为使用常规create
和destroy
方法来执行在自定义方法中执行的相同操作?
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
这将为该资源创建标准路由,并通过订阅服务器控制器路由它们。您现在需要将方法重命名为 create
、update
等。在您的控制器中。
最后,如果您通过表单到达这些端点,则需要对其进行编辑,使其指向正确的路线。
将上述行添加到routes.rb后,从终端运行rake routes
以获得所有路线的体面列表