Rails应用程序在模型间保存方面存在问题

时间:2012-06-22 15:20:25

标签: ruby-on-rails ruby

我正在开发一款从网站下载元标记然后保存的应用。下载发生在名为Site的模型中。我想将下载的漫游器元标记保存到名为robots_tag的模型中,该模型通过名为meta_tag_sites的连接表连接到网站。

但是我在网站模型中编写的方法不起作用。当我尝试在控制台中调用该方法时,出现以下错误。

  

未定义的方法`robots_meta ='for []:ActiveRecord :: Relation

知道我做错了吗?

class Site < ActiveRecord::Base
  attr_accessible :domain 
  belongs_to :user
  has_many :meta_tag_sites
  has_many :robots_tags, through: :meta_tag_sites
  accepts_nested_attributes_for :robots_tags

  # ...

  def download_robots_meta_tags
    robots_tags = Nokogiri::HTML(Net::HTTP.get(self.domain, "/")).xpath("//meta[@name='robots']")
    robots_tags.each do |tag|
      self.robots_tags.robots_meta = tag
    end
  end

  # ...

end

class RobotsTag < ActiveRecord::Base
  attr_accessible :robots_meta
  has_many :meta_tag_sites
  has_many :sites, through: :meta_tag_sites
end

class MetaTagSite < ActiveRecord::Base
  attr_accessible :site_id, :meta_tag_id
  belongs_to :site
  belongs_to :robots_tag
end

(顺便说一句,这篇文章与之前的帖子有关:Web-scraping Rails App Getting Over-Modelled?)。

2 个答案:

答案 0 :(得分:3)

问题在于:

self.robots_tags.robots_meta = tag

self.robots_tagshas_many :robots_tags定义的对象的集合,您正在尝试为整个集合分配特定属性。你不能这样做。如果要分配特定对象的属性,则必须迭代集合,或者通过firstlast或任何其他{{1}从集合中选择特定对象方法。

答案 1 :(得分:1)

通过检查,违规行似乎是:

self.robots_tags.robots_meta = tag

您应该使用以下内容迭代self.robots_tags

self.robots_tags.each do |robot_tag|
  robot_tag.robots_meta = tag
end