【问题标题】:How to create a 'star' system for a resource and write conditions based on the association如何为资源创建“星”系统并基于关联编写条件
【发布时间】:2011-02-28 13:31:03
【问题描述】:

我创建了一个 Ruby on Rails 应用程序 (2.3.9),用户可以在其中记录锻炼情况。我正在尝试实现一个“星级”系统,该系统将允许已登录的用户为他们想要记住的其他用户的锻炼加注星标。

我通过创建Star 资源(下面的关联)来做到这一点。我成功地在我的Star 表中创建了删除记录,现在想要根据 current_user 是否已经为锻炼加注星标有条件地显示视图代码。

我通过 _workouts.html.erb 的部分显示所有锻炼。对于每次锻炼,我想显示<% remote_form_for [workout, Star.new]...You have already starred this workout

Workout :has_many => :stars

User :has_many => :stars

Star :belongs_to => :workouts
Star :belongs_to => :users

我想我将不得不在 Star.rb 中创建一个 named_scope 来查看是否存在一个现有的 star 记录,其中锻炼 ID 与锻炼 ID 匹配,并且 current_user.id 与该锻炼的 star.user_id 匹配。只是打字让我很困惑。请帮忙。

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    您可以创建has_many ..., :through => ... 关系,然后使用#include? 来检查关联。

    # User
    has_many :starred_workouts, :class_name => 'Workout', :through => :stars
    
    # View
    <% if current_user.starred_workouts.include? workout %>
        ...
    

    【讨论】:

      猜你喜欢
      • 2015-04-09
      • 1970-01-01
      • 1970-01-01
      • 2020-09-18
      • 1970-01-01
      • 2013-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多