Rails从模型添加到连接表

时间:2011-05-06 23:11:45

标签: ruby-on-rails-3

目标:在通过Feed解析时找到或创建一个类别并将其添加到联接表

更新:

has_many :category_feeds
has_many :categories, :through => :category_feeds

  def self.nokogiri_get_feed(url)
    doc = Nokogiri::HTML(open(url))
    doc.search('feed entry').each do |item|
      unless exists? :guid => item.css('id').text
        categories = []
        item.xpath('content').each do |i|
          i.css('subject').each do |subject|
            name = subject['subjectname']
            categories << Category.find_or_create_by_name(name)
          end
        end
        create!(:name => item.css('title').text, :url => item.at_css("link")[:href], :guid => item['id'], :categories => categories)
      end
    end
  end

1 个答案:

答案 0 :(得分:0)

categories << Category.find_or_create_by_name(name)

我建议您在associations guide

中阅读更多内容