方法1 - 顯示/隱藏特定的列
所以,最直接的方式(如果有隻是要顯示/隱藏的東西屈指可數這將工作),只是爲了創造一個布爾列爲你需要顯示/隱藏的每一件事。所以,如果你有一個電話號碼字段,你可以有一個名爲「show_phone_number」的列,當它爲true時,它會顯示它。
方法2 - 顯示/隱藏,你可能需要整段
下一個層次是,而不是顯示/隱藏特定列,有你的顯示/隱藏布爾列類似show_contact_info
,show_photos
等每個邏輯部分,用戶將顯示或隱藏。 (你使用任何或.haml
或)
app/views/user/show.html.erb
....
<% if @user.show_contact_info %>
<%= render :partial => "user_contact_info", :locals => {:user => @user} %>
<% end %>
app/views/partials/_user_contact_info.html.erb
<%=h user.email %><br />
<%=h user.phone_number %><br />
<%= user.blog_url %><br />
...
方法3 - 顯示:
那麼在你看來,你必須像/隱藏基於誰在查看的部分
最後(和這裏的代碼沒有經過測試,但我認爲你會明白)讓我們說你的網站有一個社會結構,你想向一些人展示信息,而不是向其他人展示信息。基本上,你需要以某種形式以下或其他:
- 第能見度(誰可以查看哪些部分)
- 角色(朋友,追隨者,公立,私立)
- 一些方法,使這些關係的明確/易於理解
所以,在你User
模型,你會碰到這樣的:
class User < ActiveRecord::Base
has_many :friends, :through => "friendships" # or whatever construct you have
has_many :followers, :through => "followings" # or whatever construct you have
has_many :profile_visibilities
...
def is_friends_with(user)
friends.include?(user)
end
def is_a_follower_of(user)
user.followers.include?(self)
end
def can_see(visibilities)
visibilities.each do |v|
v.user == self || v.is_public || can_see_because_we_are_friends(v) || can_see_because_i_follow(v)
end
end
private:
def can_see_because_we_are_friends(visibility)
visibility.is_friend && is_friends_with(visibility.user)
end
def can_see_because_i_follow(visibility)
visibility.is_follower && is_follower_of(visibility.user)
end
end
然後一類叫做ProfileVisibilities
:
class ProfileVisibilities < ActiveRecord::Base
belongs_to :user
...
def is_public
visibility == "public"
end
def is_friend
visibility == "friends"
end
def is_follower
visibility == "followers"
def is_private
!is_public && !is_friend && !is_follower
end
end
則表在你的控制器稱爲profile_visibilities
id | user_id | profile_section | visibility
----------------------------------------------
1 | 1 | contact_info | public # <= visible to everyone
2 | 1 | personal_info | friends # <= visible only to "friends"
3 | 1 | blog_posts | friends # <= visible to "friends"
4 | 1 | blog_posts | followers # <= ...and followers
5 | 1 | photos | friends # <= visible only to "friends"
然後,像:
app/controllers/users_controller.rb
...
def show
@user = User.find(params[:id])
@contact_info_visibilities = ProfileVisibilities.find(:all, :conditions = ['user_id = ? AND profile_section = "contact_info"', @user.id]
@photo_visibilities = ProfileVisibilities.find(:all, :conditions = ['user_id = ? AND profile_section = "photos"', @user.id]
# ... and more for each section visibility you need
end
...
而且在您的看法:
app/views/user/show.html.erb
...
<% if current_user.can_see(@contact_info_visibilities) %>
<%= render :partial => "user_contact_info", :locals => {:user => @user}
<% end %>
<% if current_user.can_see(@photo_visibilities) %>
<%= render :partial => "user_photos", :locals => {:user => @user}
<% end %>
...
信息添加到的問題!我現在要刪除我的評論。 – tvalent2