簡體   English   中英

Rails應用程序無法保存模型間的麻煩

[英]Rails app has trouble with inter-model saving

我正在開發一個從網站下載元標記並保存的應用程序。 下載發生在稱為Site的模型中。 我想meta標簽保存關閉下載到機器人的模型稱為robots_tag它通過稱為連接表連接到網站meta_tag_sites

但是我在站點模型中編寫的用於此目的的方法不起作用。 當我嘗試在控制台中調用該方法時,出現以下錯誤。

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

知道我在做什么錯嗎?

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抓取Rails App是否過建模? )。

問題在這里:

self.robots_tags.robots_meta = tag

self.robots_tagshas_many :robots_tags定義的對象的集合 ,您正嘗試為整個集合分配特定的屬性。 你做不到 如果要分配給特定對象的屬性,則必須迭代集合,或者通過firstlast或任何其他Enumerable方法從集合中選擇特定對象。

經檢查,違規行似乎是:

self.robots_tags.robots_meta = tag

您應該改為使用類似以下內容的方法遍歷self.robots_tags

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM