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一起工作?或者,有沒有更好的方法來設計這個?我正在考慮使用多對多而不是嵌入式。
你的想法是什麼?
之後,
順便說一句,上面的實現工作。我只是想看看我是否做得對,或者是否有更清晰的方法 – 2010-11-17 12:37:22