通过remote_form删除关联记录
我构建了一个 Ruby on Rails 应用程序,可以让用户跟踪他们的锻炼情况。用户有_很多次锻炼。此外,如果用户是健身房所有者,则可以创建一个盒子(健身房)。然后,用户可以通过成员资格资源与该框关联。
我在 /views/boxes/show.html.erb 中为 current_user 创建了与远程表单的关联:
<% remote_form_for Membership.new do |f| %>
<%= f.hidden_field :box_id, :value => @box.id %>
<%= f.hidden_field :user_id, :value => current_user.id %>
<%= submit_tag "I am a member of this box" , :class => '' %>
<% end %>
我现在想让 current_user 能够删除其关联。如何构建链接/表单以及memberships_controller 销毁操作应该是什么样子?
以下是我的协会列表(如果有帮助的话): 用户
class User < ActiveRecord::Base
has_many :boxes
has_many :workouts, :dependent => :destroy
end
健身
class Workout < ActiveRecord::Base
belongs_to :user
belongs_to :box
end
盒
class Box < ActiveRecord::Base
belongs_to :user
has_many :users, :through => :memberships
has_many :workouts, :through => :users
has_many :memberships
end
会员资格
class Membership < ActiveRecord::Base
belongs_to :user
belongs_to :box
end
I have built a ruby on rails app that lets users track their workouts. User has_many workouts. In addition, a User can create a box (gym) if they are a gym owner. Users can then associate with that box through a Membership resource.
I create that association for the current_user with a remote form in /views/boxes/show.html.erb:
<% remote_form_for Membership.new do |f| %>
<%= f.hidden_field :box_id, :value => @box.id %>
<%= f.hidden_field :user_id, :value => current_user.id %>
<%= submit_tag "I am a member of this box" , :class => '' %>
<% end %>
I now want to give the current_user the ability to remove their association. How do I structure the link/form and what should the memberships_controller destroy action look like?
Below is a list of my associations if it helps:
User
class User < ActiveRecord::Base
has_many :boxes
has_many :workouts, :dependent => :destroy
end
Workout
class Workout < ActiveRecord::Base
belongs_to :user
belongs_to :box
end
Box
class Box < ActiveRecord::Base
belongs_to :user
has_many :users, :through => :memberships
has_many :workouts, :through => :users
has_many :memberships
end
Membership
class Membership < ActiveRecord::Base
belongs_to :user
belongs_to :box
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
完成此处建议的更改后,并假设您已使用以下代码获取了 current_user 和 box 的成员资格,
请为用户创建一个链接以删除成员资格,如下所示。
成员资格控制器应该有一个如下所示的销毁方法。
这是假设您的会员控制器是静态的,并且您的路线中有
map.resources :memberships
。After you have done the changes suggested here, and assuming that you have obtained the membership for the current_user and the box using the following code,
create a link for the user to delete the membership as follows.
Membership controller should have a destroy method that looks like the following.
This is assuming that your memberships controller is restful and you have
map.resources :memberships
in your routes.