在 Ruby on Rails 中仅删除连接表记录
我有以下简单的模型:
class Event < ActiveRecord::Base
has_many :participations
has_many :users, :through => :participations
end
class Participation < ActiveRecord::Base
belongs_to :event
belongs_to :user
end
class User < ActiveRecord::Base
has_many :participations
has_many :events, :through => :participations
end
在我看来,我想做的是,根据当前用户的角色,删除事件及其参与记录,或者仅删除参与记录本身。
我目前有
<%= link_to '删除事件', event, :confirm => '你确定吗?', :方法=> :删除%>
这会删除事件及其参与。我还需要采取其他行动吗?或者可以劫持Event的销毁动作?它会是什么样子?
谢谢
I have the following simple models:
class Event < ActiveRecord::Base
has_many :participations
has_many :users, :through => :participations
end
class Participation < ActiveRecord::Base
belongs_to :event
belongs_to :user
end
class User < ActiveRecord::Base
has_many :participations
has_many :events, :through => :participations
end
What I would like to do in my view is, dependant on the current users role, delete either an event and its participation record, or just a participation record on its own.
I currently have
<%= link_to 'Delete event', event, :confirm => 'Are you sure?',
:method => :delete %>
which deletes both event, and its participation. Do I need another action? or can hijack the destroy action of Event? What would it look like?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
嗯,在视图助手中,黑客可能是这样的:
在您看来,您可以使用 link_to_delete_event( event ) 单独删除事件,并使用 link_to_delete_event( event,participation )< /strong> 删除参与。您的控制器可能是这样的:
编辑
为了减少黑客攻击,您应该为事件下的参与创建一个嵌套资源:
然后您必须创建一个ParticipationsController >,它可能看起来像这样:
并且 link_to 帮助器将更改为:
Well, a hack could be something like this, in a view helper:
And in your view you'd use link_to_delete_event( event ) to delete an event alone and link_to_delete_event( event, participation ) to delete the participation. Your controller could be something like this:
EDIT
To make it less of a hack you should create a nested resource for participations under events:
And then you'll have to create a ParticipationsController, which could look like this:
And the link_to helper would change to this: