【问题标题】:Restricting a portion of code through an association通过关联限制部分代码
【发布时间】:2010-12-02 13:46:30
【问题描述】:

我已经构建了一个 ruby​​ on rails 应用程序,可以让用户跟踪他们的锻炼情况。用户 has_many 锻炼。此外,如果用户是健身房的所有者,他们可以创建一个盒子(健身房)。目的是过滤用户的活动,以便他们只能看到与其健身房相关的信息。然后,用户可以通过 Membership 模型指定他们是否是该框的成员。 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 %>

我试图将表单限制为仅不是该框成员的用户,但我不确定如何编写 &lt;% unless ... %&gt; 语句。

以下是其余的关联:

用户

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

【问题讨论】:

  • 我猜有些人会从所有代码中受益,但有时阅读太多了:)

标签: ruby-on-rails ruby model associations


【解决方案1】:
# 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 %>

免责声明:代码未经测试。它可能需要稍作改动。

【讨论】:

  • 我遇到了一个错误。 undefined method for_box' 用于#<0x104c2df80>
  • &gt;&gt;&gt;&gt;
  • &gt;&gt;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-10
  • 2014-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多