ruby on rails - Restricting a portion of code through an association -
i have built ruby on rails app lets users track workouts. user has_many workouts. in addition, user can create box (gym) if gym owner. purpose filter activity of users such can see information related gym. users can specify if member of box through membership model. membership table collects @box.id , current_user.id in membership.box_id , user.id columns respectively.
the user associates through following form in /views/boxes/show.html.erb view:
<% remote_form_for membership.new |f| %> <%= f.hidden_field :box_id, :value => @box.id %> <%= f.hidden_field :user_id, :value => current_user.id %> <%= submit_tag "i member of box" , :class => '' %> <% end %>
i display, in box show page users members of box.
<% @box.users.each |user| %> <%= link_to (user.username), user %><br/> <% end %>
i trying restrict form users not members of box not sure how write <% unless ... %>
statement.
here rest of associations:
user
class user < activerecord::base has_many :boxes has_many :workouts, :dependent => :destroy end
workout
class workout < activerecord::base belongs_to :user belongs_to :box end
box
class box < activerecord::base belongs_to :user has_many :users, :through => :memberships has_many :workouts, :through => :users has_many :memberships end
membership
class membership < activerecord::base belongs_to :user belongs_to :box end
# 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 form <% end %>
disclaimer: code not tested. might need minor alterations.
Comments
Post a Comment