2010-11-17 91 views
0

我有隐私设置供用户设置。隐私设置可以是这样:操作方法用户有很多隐私设置

  • 不显示在公共时间轴我的更新
  • 不显示我的电子邮件地址
  • 不显示我的出生日期

我认为具有嵌入在用户集合中的隐私设置。

class User 
    include Mongoid::Document 
    include Mongoid::Timestamps 

    embeds_many :privacies 
    ... 
end 

class Privacy 
    include Mongoid::Document 

    field :title, :type => String 
    field :description, :type => String 
    field :is_active, :type => Boolean 

    embedded_in :user, :inverse_of => :privacies 
    ... 
end 

我的形式看起来像:

<%= form_for(@user, :url => user_path(@user)) do |f| %> 
    <ul> 
    ... 
    <% @user.notifications.each do |notification| %> 
     <li> 
     <%= check_box_tag 'user[notifications][]', notification.id, notification.is_active %> 
     <%= label_tag notification.description %> 
     </li> 
    <% end %> 

    <li class="clearfix"> 
     <%= image_submit_tag('update.png', :class => 'submit') %> 
    </li> 
    </ul> 
<% end %> 

当表单提交。它有以下参数:

{"utf8"=>"✓", "_method"=>"put", 
"authenticity_token"=>"FQvGlJ8p+SPX8MIQqMjS04tHVLQ4jEl31tpAoKwGYDE=", "user"=>{"city_id"=>"", 
"notifications"=>["4ce3c66872357e0a95000011", "4ce3c66872357e0a95000012"]}, "action"=>"update", 
"controller"=>"users", "id"=>"1234"} 

正如你可以从上面看到的。其提交通知ID作为数组:“通知”=> [ “4ce3c66872357e0a95000011”, “4ce3c66872357e0a95000012”]}

以我的用户控制器,更新方法。我有:

def update 
    @user = User.where(:id => params[:id]).first 

    # Unset all notifications for user 
    @user.notifications.each do |notification| 
    notification.update_attributes!(:is_active => false) 
    end 

    # Based on the form, set notifications 
    params[:user][:notifications].each do |notification| 
    @user.notifications.find(notification).update_attributes!(:is_active => true) 
    # @user.notifications.first.update_attributes!(:is_active => false) 
    end 

    # Remove the notifications from params 
    params[:user][:notifications] = [] 

    respond_to do |format| 
    if @user.update_attributes(params[:user]) 
    ... 
    end 
end 

我的更新方法看起来有点乱,因为:IS_ACTIVE为false:

1)我通过设置重置所有复选框。

2)之后,我正在查看所有通知ID的参数,并将每个参数的is_active设置为true。

3)最后,我从params中删除通知数组,否则我的表单不能正确保存。

有没有更好的/更清洁的方式让它与Mongoid一起工作?或者,有没有更好的方法来设计这个?我正在考虑使用多对多而不是嵌入式。

你的想法是什么?

之后,

+0

顺便说一句,上面的实现工作。我只是想看看我是否做得对,或者是否有更清晰的方法 – 2010-11-17 12:37:22

回答

0

看起来不错。你可以把它清理一下,但不会有太大的变化。

I.e.

# loop and set these to false 
user.notifications.not_in(:id => params[:user][:notifications]) 

# loop and set these to true 
user.notifications.any_in(:id => params[:user][:notifications])