简体   繁体   English

如何从关联的模型中提取信息(Rails)

[英]How to pull information from associated model (Rails)

I'm running a search using the Ransack gem. 我正在使用Ransack gem运行搜索。

Controller code (for ItemsController) 控制器代码(用于ItemsController)

@q = Item.search(params[:q])
@search_results = @q.result

After running the search, @search_results contains multiple Items (Item 1, Item 2, Item 3, …). 运行搜索后, @search_results包含多个Items (项目1,项目2,项目3等)。 Where each Item is a hash: 每个项目都是哈希值:

Item = { "id" => "12", "name" => "shovel", "user_id" => "2", "type" => "A" }

In this case, for each Item hash, I want to add an additional key-value pair that translates the user_id into the name that is associated with that instance of the User model (ie, User has_many :Items and Item belongs_to :Users ) 在这种情况下,对于每个Item哈希,我想添加一个附加的键-值对,该对将user_id转换为与User模型的该实例相关联的名称(即, User has_many :ItemsItem belongs_to :Users

I tried in the same controller code section 我在同一控制器代码部分中尝试过

@search_results.each do |item|
    item[:user_name] = User.find_by_id(item.user_id).name
end

But I get an error that I can't write to item. 但是我收到一个我无法写到项目的错误。 I suspect Ransack has something to do with it though, because if I just print @search_results , instead of getting the actual Item data, I get #<ActiveRecord::Relation::ActiveRecord_Relation_Item:0x000001025e6c78> 我怀疑Ransack与此有关,因为如果我只打印@search_results ,而不是获取实际的Item数据, @search_results得到#<ActiveRecord::Relation::ActiveRecord_Relation_Item:0x000001025e6c78>

Help greatly appreciated! 帮助极大的赞赏!

Btw, in case there's even an easier way, the reason I want to add another key/value pair with the user_name is because the ultimate output is a JSON that is being picked up by another part of the codebase, and we don't want to run two separate database queries. 顺便说一句,如果有更简单的方法,我想用user_name添加另一个键/值对的原因是因为最终输出是JSON,而该JSON已被代码库的另一部分拾取,我们不希望运行两个单独的数据库查询。

Firstly, you're receiving a ruby object back, which I take means you can create a set of attributes for in the model. 首先,您将收到一个红宝石对象,这意味着您可以在模型中创建一组属性。 Why don't you try using a getter in your item model to set for you: 为什么不尝试在item模型中使用吸气剂为您设置:

#app/models/item.rb
Class Item < ActiveRecord::Base
    belongs_to :user #-> needs to be singular
    attr_accessor :user_name

    def user_name
       self.user.name
    end
end

This means that instead of having to append a user_name attribute from your controller, every Item object will automatically have the user_name attribute anyway 这意味着不必从控制器中添加user_name属性,而是每个Item对象将自动具有user_name属性

A refactor of this would also be to use the delegate method inside your Item model: 对此的重构也将是在Item模型中使用delegate方法

Class Item < ActiveRecord::Base
    belongs_to :user
    delegate :name, to: :user, prefix: true #-> allows you to call @item.user_name
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM