我在 Rails 中有以下多对多关系(当然是 ActiveResource):
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
定义的路线:
map.resources :users, :has_many => :channel_assignments
更新: rake routes 给出以下输出:
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"}
由于 ChannelAssignemnts 绑定到用户,我使用我的脚手架 ChannelAssignmentsController 在创建 ChannelAssignment 时自动将用户分配给通道。
我通过使用这些 URL 来做到这一点:
#/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| %>
...
这很迷人。
但是:取消分配频道的路径是什么,ergo:删除用户的ChannelAssignment?运行 rake 路由时找不到它。
必须是类似的东西
<%= link_to 'Destroy', delete_user_channel_assignment, :user_id => @user, :method => :delete %>
对此有任何意见吗?我确信有一种方法可以自动生成此 URL。
谢谢
马特