从视图中获取逻辑...named_scope 帮助
我创建了一个应用程序,允许用户记录他们的锻炼。
用户能够保留其锻炼的私人或公开日志,并由将整数 1
传递到锻炼.share 列的 check_box 字段表示。私人日志可以通过executors_controller查看,我通过过滤current_user来限制所有输出。
锻炼_controller.rb
@workouts = current_user.Workouts.all
公共锻炼通过单独的社区_控制器显示,我在那里将锻炼称为
社区_控制器
@workouts = Workouts.all
,然后使用以下内容过滤视图中的结果
<% @workouts.each do |workout| %>
<% if workout.share == 1 %>
...
<% end %>
<% end %>
我可以告诉你这不是首选方法,我怀疑是我想要一个命名范围,以便我可以创建一个新变量“@shared_workouts”。也就是说,我不熟悉命名范围,因此可以使用一些帮助来了解在哪里放置什么以及正确的语法。
I have created an application where I am allowing users to log their Workouts.
The user has the ability to keep a private or public log of their workouts and is denoted by a check_box field that passes the integer 1
to the workout.share column. The private log is viewable through the workouts_controller where I am limiting all output by filtering for current_user.
workouts_controller.rb
@workouts = current_user.Workouts.all
The public workouts are shown through a separate community_controller and there I call the workouts like this
community_controller
@workouts = Workouts.all
and then filtering the results in the view with the following
<% @workouts.each do |workout| %>
<% if workout.share == 1 %>
...
<% end %>
<% end %>
Best I can tell this is not the preferred way to do this and my suspicion is that I want a named_scope such that I can create a new variable `@shared_workouts'. That said I am not familiar with named scopes so could use some help on where to put what and the correct syntax.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您使用的是 Rails 2,请使用以下命令:
如果您使用的是 Rails 3,请使用以下命令:
然后在社区控制器中,您可以简单地使用
@workouts = Workouts.shared.all
If you are using rails 2, use the following:
If you are using rails 3, use this instead:
Then in the community controller, you could simply use
@workouts = Workouts.shared.all
正如Peter上面提到的,根据您使用的Rails版本使用named_scope/scope。另外,您不想使用值 1 进行测试。您想要使用 true (也就是说,如果您在迁移中使用了 boolean 类型)。
原因是,如果您更改数据库,它可能会以不同的方式存储(例如,SQLite 有一个布尔类型,mySQL 使用一个小整数...),并且活动记录将为您管理它。 :)
或者
然后使用“Workouts.shared”访问named_scope。
As Peter mentions above, use a named_scope / scope according to the Rails version you use. Also you don't want to use the value 1 for you test. You want to use true (that is if you have used the type boolean in your migration).
The reason is if you change database it may be stored differently (SQLite has a boolean type for example, mySQL uses a tiny int...), and active record will manage it for you. :)
Or
Then use "Workouts.shared" to access the named_scope.