2010-12-02 29 views
1

我在rails應用上構建了一個ruby,可以讓用戶跟蹤他們的鍛鍊。用戶has_many鍛鍊。另外,如果用戶是健身房老闆,用戶可以創建一個箱子(健身房)。目的是過濾用戶的活動,使他們只能看到與他們健身房相關的信息。用戶然後可以通過成員資格模型指定他們是否是該框的成員。 Membership表分別收集membership.box_id和user.id列中的@ box.id和current_user.id。通過關聯限制部分代碼

在/views/boxes/show.html.erb視圖通過以下形式向用戶聯繫人:

<% remote_form_for Membership.new do |f| %> 
    <%= f.hidden_field :box_id, :value => @box.id %> 
    <%= f.hidden_field :user_id, :value => current_user.id %> 
    <%= submit_tag "I am a member of this box" , :class => '' %> 
<% end %> 

我然後顯示,在框中顯示頁的所有誰是那個盒子的成員的用戶。

<% @box.users.each do |user| %> 
    <%= link_to (user.username), user %><br/> 
<% end %> 

我試圖限制形式只是誰是不是已經那個盒子的成員的用戶,但我不知道該怎麼寫<% unless ... %>聲明。

這裏有關聯的其餘部分:

用戶

class User < ActiveRecord::Base 
    has_many :boxes 
    has_many :workouts, :dependent => :destroy 
end 

鍛鍊

class Workout < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :box 
end 

class Box < ActiveRecord::Base 
    belongs_to :user 
    has_many :users, :through => :memberships 
    has_many :workouts, :through => :users 
    has_many :memberships 
end 

會員

class Membership < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :box 
end 
+0

我想有些人會受益於所有的代碼,但它有時候太多了:) – s84 2010-12-02 04:50:25

回答

0
# Membership model 
named_scope :for_box, lambda {|box| {:conditions => {:box_id => box.id}}} 

# User model 
has_many :memberships 

def member_of_box?(box) 
    !memberships.for_box(box).blank? 
end 

# View 
<% unless current_user.member_of_box?(box) %> 
    # Show the form 
<% end %> 

聲明:該代碼是未經測試。它可能需要較小的改動。

+0

我得到一個錯誤。 `未定義的方法`for_box'for#` – bgadoci 2010-12-02 05:28:41