Ben Downey
Ben Downey

Reputation: 2665

Rails models not talking with each other. Not sure how to add records to one model from within another

I'm working on an app that does some web scraping. In the sites model, I've got this method:

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

The sites model has many robots_tags through a join table called robots_tag_sites. The sites model also accepts_nested_attributes_for :robots_tags. The method above is meant to take all the tags that get downloaded in line 1 of the method and save them off to the tags column of the robots_tags table.

I think the problem is that "self.robots_tags" still grabs a collection of things instead of one individual thing. But I'm not sure how to add the tag correctly. Any advice?

(BTW, these is a follow up from another post, Rails app has trouble with inter-model saving)

Upvotes: 0

Views: 60

Answers (1)

user229044
user229044

Reputation: 239290

You should be using self.robots_tags.create(...) to create a new RobotTag object.

Assuming your RobotTag has a tag attribute, it might look something like this:

downloaded_tags.each do |t|
  self.robot_tags.create(:tag => t)
end

Upvotes: 5

Related Questions