【问题标题】:undefined method 'id_tag' for ActiveRecord_Associations_CollectionProxyActiveRecord_Associations_CollectionProxy 的未定义方法“id_tag”
【发布时间】:2016-07-21 11:27:53
【问题描述】:

在我的 CrawlProduct 类中,我想从 ProductInfo 表中获取 id_tag:

class CrawlProduct < ActiveRecord::Base
    belongs_to :crawl_link

    css_id = self.crawl_link.domain.product_infos.id_tag
end

表CrawlProducts 有一个外键crawl_link,而表CrawlLinks 有一个外键domain,当然它来自表Domain。 ProductInfo 属于域。

class CrawlProduct < ActiveRecord::Base
        belongs_to :crawl_link 
end   

class CrawlLink < ActiveRecord::Base
        belongs_to :domain
        has_one :crawl_product
end

class Domain < ActiveRecord::Base
        has_many :crawl_links
        has_many :product_infos
end

class ProductInfo < ActiveRecord::Base
        belongs_to :domain
end

但最后,我总是收到以下错误:

undefined method `id_tag' for #<ProductInfo::ActiveRecord_Associations_CollectionProxy:0x0055d72e423640>

如何访问id_tag?据我所知,没有一列缺失。

编辑:在回答之后我得到一个不同的错误。

NameError: undefined local variable or method `id_tag' for #<CrawlProduct:0x0055d72fcd9fe0>

我不知道为什么会遇到这个问题。以下是我创建 id_tag 的方法:

class Domain < ActiveRecord::Base
   domain = Domain.create(domain: 'https://www.example.com')
   product_info = ProductInfo.create(domain: domain, id_tag: 'some content')
end

【问题讨论】:

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


    【解决方案1】:

    我认为您错误地访问了product_infos。您需要指定您想要的,然后从中访问 id_tag。

    Rails 正确地告诉你

    undefined method `id_tag' for #<ProductInfo::ActiveRecord_Associations_CollectionProxy:0x0055d72e423640>
    

    因为关系是has_many。

    如果您只想访问数据库提取的第一个(没有特定顺序,除非您指定),您可以这样做

    css_id = self.crawl_link.domain.product_infos.first.id_tag
    

    【讨论】:

      【解决方案2】:

      self.crawl_link.domain.product_infos 是实例的集合,因此您不能对其调用实例方法,要在每个项目上调用它,您应该使用each 迭代集合或使用map 收集ID。要仅收集 id 而不创建实例,您可以使用 pluck:

      self.crawl_link.domain.product_infos.pluck(:id_tag)
      

      【讨论】:

        【解决方案3】:

        self.crawl_link.domain.product_infos 将返回一组对象,因此您无法从集合中检索 id_tag(字段)。

        你可以使用,.

        class CrawlProduct < ActiveRecord::Base
            belongs_to :crawl_link
        
            def some_action
              css_ids = self.crawl_link.domain.product_infos.pluck(:id_tag)
        
              (or)
        
              css_ids = self.crawl_link.domain.product_infos.map(&:id_tag)
            end
        end
        

        【讨论】:

        • 感谢您的帮助,但我仍然收到错误消息。我编辑了我的问题
        • 添加您正在使用这些行的操作
        • 您是直接从模型中调用css_id 吗?
        猜你喜欢
        • 2015-10-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-17
        • 1970-01-01
        相关资源
        最近更新 更多