【问题标题】:Getting the logic out of the view...help with named_scope从视图中获取逻辑...帮助 named_scope
【发布时间】:2010-11-19 02:26:58
【问题描述】:

我创建了一个允许用户记录锻炼的应用程序。

用户可以保留其锻炼的私人或公共日志,并由一个复选框字段表示,该字段将整数 1 传递给锻炼.share 列。可以通过锻炼控制器查看私人日志,我通过过滤 current_user 来限制所有输出。

workouts_controller.rb

@workouts = current_user.Workouts.all

公开锻炼通过单独的 community_controller 显示,我将锻炼称为这样

community_controller

@workouts = Workouts.all

然后在视图中过滤结果如下

<% @workouts.each do |workout| %>
 <% if workout.share == 1 %> 
  ...
 <% end %>
<% end %>

我可以说这不是首选的方法,我怀疑我想要一个 named_scope,这样我就可以创建一个新变量“@shared_workouts”。那就是说我不熟悉命名范围,因此可以使用一些帮助来确定放置内容的位置和正确的语法。

【问题讨论】:

    标签: ruby-on-rails ruby named-scope


    【解决方案1】:

    如果您使用的是 rails 2,请使用以下内容:

    class Workout < ActiveRecord::Base
      named_scope :shared, :conditions => {:share => 1}
    end
    

    如果您使用的是 rails 3,请改用它:

    class Workout < ActiveRecord::Base
      scope :shared, where(:share => 1)
    end
    

    然后在社区控制器中,您可以简单地使用@workouts = Workouts.shared.all

    【讨论】:

      【解决方案2】:

      正如 Peter 上面提到的,根据您使用的 Rails 版本使用 named_scope / 范围。此外,您不想使用值 1 进行测试。您想使用 true(也就是说,如果您在迁移中使用了 boolean 类型)。

      原因是如果您更改数据库,它可能会以不同的方式存储(SQLite 有一个布尔类型,例如,mySQL 使用一个小整数...),活动记录将为您管理它。 :)

      class Workout < ActiveRecord::Base
        named_scope :shared, :conditions => {:share => true}
      end
      

      或者

      class Workout < ActiveRecord::Base
        scope :shared, where(:share => true)
      end
      

      然后使用“Workouts.shared”访问named_scope。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多