【问题标题】:Rails - pull attribute value from table using two conditionsRails - 使用两个条件从表中提取属性值
【发布时间】:2016-05-08 13:40:25
【问题描述】:

我的 rails 应用程序中有两个表:一个用户表和一个活动表。用户有很多活动。现在,我正在尝试找出如何打印出activity_name,其中activity_type = :personal AND where user_id = current_user.id。

在我的活动索引文件中,我有以下内容:

<% @activities.where(:user_id => current_user.id).where(:activity_type => :personal).each do |activity| %>
<%= activity.activity_name %>
<% end %>

页面上什么都没有打印出来——我肯定已经将用户和活动添加到数据库中,因为我已经检查了 rails 控制台。我是否错误地设置了每个执行循环?有没有其他方法可以查询这些数据?

【问题讨论】:

    标签: ruby-on-rails database sqlite model-view-controller querying


    【解决方案1】:

    应该这样写:

    <% @activities.where(user_id: current_user.id, activity_type: "personal").each do |activity| %>
      <%= activity.activity_name %>
    <% end %>
    

    或者比这更好,因为用户has_many活动:

    <% current_user.activities.where(activity_type: "personal").each do |activity| %>
      <%= activity.activity_name %>
    <% end %>
    

    我们可以使用范围进一步压缩它:

    class Activity < ActiveRecord::Base
      def self.personal
        where(activity_type: "personal")
      end
    end
    

    在控制器中:

    def index # or whatever you wnat
      @activities = current_user.activities.personal
    end
    

    观点:

    <% @activities.each do |activity| %>
      <%= activity.activity_name %>
    <% end %>
    

    【讨论】:

    • 谢谢,我将其更改为以下内容,但视图上仍然没有打印任何内容。为什么会发生这种情况有什么原因吗?

    • 从哪里来@activities
    • 来自我的活动控制器:class ActivitiesController
    • 您确定您的数据库中有活动吗?打开 rails 控制台:rails console 来自您的 terminal 并输入 Activity.count
    • 好的,如果您删除 where 条件,它会显示 10 个活动吗?
    【解决方案2】:

    如果您有用户的活动关联,您应该能够执行类似的操作

    current_user.activities.where(activity_type: :personal)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-02
      • 1970-01-01
      • 2017-05-26
      • 1970-01-01
      • 1970-01-01
      • 2017-02-25
      • 2018-01-20
      • 1970-01-01
      相关资源
      最近更新 更多