URL de exclusão para associações aninhadas
-
06-07-2019 - |
Pergunta
Eu estou tendo o seguinte muitos para muitos relação em Rails (ActiveResource, é claro):
class User < ...
has_many :channel_assignments
has_many :channels, :through => :channel_assignments
end
class Channel < ...
has_many :channel_assignments
has_many :users :through => :channel_assignments
end
class ChannelAssignment < ...
belongs_to :user
belongs_to :channel
end
rotas definidas:
map.resources :users, :has_many => :channel_assignments
Update: rake routes dá o seguinte resultado:
user_channel_assignments GET /users/:user_id/channel_assignments(.:format) {:action=>"index", :controller=>"channel_assignments"}
POST /users/:user_id/channel_assignments(.:format) {:action=>"create", :controller=>"channel_assignments"}
new_user_channel_assignment GET /users/:user_id/channel_assignments/new(.:format) {:action=>"new", :controller=>"channel_assignments"}
edit_user_channel_assignment GET /users/:user_id/channel_assignments/:id/edit(.:format) {:action=>"edit", :controller=>"channel_assignments"}
user_channel_assignment GET /users/:user_id/channel_assignments/:id(.:format) {:action=>"show", :controller=>"channel_assignments"}
PUT /users/:user_id/channel_assignments/:id(.:format) {:action=>"update", :controller=>"channel_assignments"}
DELETE /users/:user_id/channel_assignments/:id(.:format) {:action=>"destroy", :controller=>"channel_assignments"}
Como ChannelAssignemnts são obrigados a usuário, eu estou usando meu scaffolded ChannelAssignmentsController para automaticamente atribuir um usuário a um canal ao criar um ChannelAssignment.
Eu estou fazendo isso usando essas URLs:
#/app/views/users/index.html.erb
#show a link to view all channels of a user
<%= link_to 'Channels', user_channel_assignments_path(user) %>
...
#/app/views/channel_assignments/new.html.erb
#assign a channel to currently selected user
<% form_for(@channel_assignment, :url => user_channel_assignments_path(@user) ) do |f| %>
...
Isso encantadoramente funciona.
Mas: Qual é o caminho para o canal A unassign, ergo: para apagar ChannelAssignment de um usuário? não pode encontrá-lo quando estiver executando rake routes.
Deve ser algo como
<%= link_to 'Destroy', delete_user_channel_assignment, :user_id => @user, :method => :delete %>
Qualquer entrada sobre este assunto? Eu tenho certeza que há uma maneira de autmatically geraram esta URL.
Graças
Matt
Solução
Você só precisa usar o verbo de exclusão em seu link:
<%= link_to 'Destroy', user_channel_assignment(:user_id => @user, :id => @channel), :method => :delete %>
Ele também deve ser visível em rake routes -. Apenas com o verbo de exclusão