尝试使用checkboxes和has_many创建/删除多个关联:through

时间:2013-10-14 15:58:25

标签: ruby-on-rails activerecord nested-attributes

这是我的模特的样子。用户可以根据他们的群组(用户HABTM群组HABTM频道)以及他们订阅的频道订阅多个频道(用户HM频道T订阅,我没有在这里使用HABTM,因为订阅将具有显示顺序列)。

class User < ActiveRecord::Base
  has_and_belongs_to_many :groups
  has_many :subscriptions
  has_many :channels, through: :subscriptions
end

class Group < ActiveRecord::Base
  has_and_belongs_to_many :users
  has_and_belongs_to_many :channels
end

class Channel < ActiveRecord::Base
  has_and_belongs_to_many :groups
  has_many :subscriptions
  has_many :users, through: :subscriptions
end

class Subscription < ActiveRecord::Base
  belongs_to :user
  belongs_to :channel
end

我所做的是显示用户可以订阅的所有频道的列表(如果只有一个SQL语句有更简单的方法可以让我知道):

@channels = Channel.joins(
  'JOIN channels_groups ON channels.id = channels_groups.channel_id', 
  'JOIN groups_users ON channels_groups.group_id = groups_users.group_id', 
  'JOIN users ON groups_users.user_id = users.id'
).where('users.id = ?', @user.id).uniq

我无法弄清楚如何在此频道列表周围创建一个复选框形式。理想情况下,我希望能够

  1. 创建用户已选中的订阅(如果不是) 存在,
  2. 并删除用户取消选中的订阅 它们存在。
  3. 这是嵌套属性吗?

1 个答案:

答案 0 :(得分:0)

结束这样做。认为它可以改进吗?

在我看来:

<% for channel in @channels do %>
  <%= check_box_tag "subscription[][channel_id]", channel.id, @user.channels.include?(channel) %>
  <%= channel.name %>
<% end %>

<%= hidden_field_tag "subscription[][channel_id]", "" %>
<%= submit_tag %>

然后在我的控制器中:

# get all of a users subscriptions that weren't checked and delete them
@user.subscriptions.where('channel_id IN (?)', @user.channel_ids - params[:subscription].map{ |s| s['channel_id'].to_i }.flatten).delete_all
# then add all those that were checked
Subscription.create(params[:subscription]) { |s| s.user_id = @user.id }