Rails 应用程序在模型间保存方面存在问题 [英] Rails app has trouble with inter-model saving
问题描述
我正在开发一款从网站下载元标记并保存的应用.下载发生在一个名为 Site
的模型中.我想将下载的机器人元标记保存到一个名为 robots_tag
的模型中,该模型通过名为 meta_tag_sites
的连接表连接到站点.
I'm working on an app that downloads meta tags from websites and saves then. The downloading happens in a model called Site
. I'd like to save off the downloaded robots meta tags into a model called robots_tag
which is connected to sites via a join table called meta_tag_sites
.
但是我在站点模型中编写的用于执行此操作的方法不起作用.当我尝试在控制台中调用该方法时,出现以下错误.
But the method that I've written in the sites model to do this isn't working. When I try to call the method in the console, I get the following error.
未定义方法`robots_meta=' for []:ActiveRecord::Relation
undefined method `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-scrapingRails 应用过度建模?).
(BTW, this post is related to an earlier post: Web-scraping Rails App Getting Over-Modelled?).
推荐答案
问题出在这里:
self.robots_tags.robots_meta = tag
self.robots_tags
是由 has_many :robots_tags
定义的对象的集合,并且您正在尝试为其分配特定属性整个集合.你不能这样做.如果要分配给特定对象的属性,则必须遍历集合,或通过 first
或 last
或任何方法从集合中选择特定对象其他 Enumerable
方法.
self.robots_tags
is a collection of objects defined by has_many :robots_tags
, and you're attempting to assign a specific attribute to that entire collection. You can't do this. If you want to assign to an attribute on a specific object, you have to either iterate over the collection, or select a specific object from the collection via first
or last
or any of the other Enumerable
methods.
这篇关于Rails 应用程序在模型间保存方面存在问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!