2013-10-14 55 views
0

這是我的模型的樣子。用戶可以根據他們的組(用戶HABTM組HABTM頻道)以及他們訂閱的頻道訂閱許多頻道(用戶HM頻道T訂閱,這裏我沒有使用HABTM,因爲訂閱將有一個顯示順序列)。嘗試使用複選框和has_many創建/刪除多個關聯:通過

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. 並刪除那些用戶選中如果 它們存在訂閱。

這是一個嵌套的屬性,形成東西?

回答

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 }