【问题标题】:Rails: Get only certain attributes of submodel with method 'attributes'Rails:使用方法“属性”仅获取子模型的某些属性
【发布时间】:2013-03-11 11:03:42
【问题描述】:

有没有办法像这样只获取外国模型的某些字段:

@user = User.find(:first, :select => ['`users`.`id`, `users`.`nickname`, `users`.`birthdate`, `users`.`sex`'], :conditions => ['`users`.`id` = ?', id])

city = @user.profile.city.attributes

使用attributes,我检索了我的城市模型的所有属性。我只想得到一些。比如:

city = @user.profile.city.attributes[:name, :postcode]

是否可以通过保持语法像上面一样简单?我想使用attributes 来接收哈希。

非常感谢。

【问题讨论】:

    标签: ruby-on-rails activerecord ruby-on-rails-3.2


    【解决方案1】:

    如果您不介意它在 SQL 返回所有内容后挑选字段,您可以这样做:

    @user.profile.city.attributes.select{|k,v| ["name","postcode"].include?(k)}
    

    【讨论】:

      【解决方案2】:

      以您的方式链接时,无法选择外国模型的字段。唯一的方法是对 City 模型进行查询:

      City.where(:profile_id => @user.profile.id, :select => ...)
      

      【讨论】:

        【解决方案3】:

        你不能在属性之后进行争论,否则会引发 ArguementError。在这种情况下,您可以使用内部连接来获取记录。

        【讨论】:

          【解决方案4】:
          city = @user.profile.city.pluck(:name, :postcode)
          

          【讨论】:

            猜你喜欢
            • 2011-07-15
            • 2023-03-21
            • 2017-04-14
            • 1970-01-01
            • 2021-03-06
            • 1970-01-01
            • 1970-01-01
            • 2019-05-01
            • 2014-05-04
            相关资源
            最近更新 更多