gpt4 book ai didi

ruby-on-rails - Rails Mechanize 连接表循环

转载 作者:行者123 更新时间:2023-12-04 16:18:57 25 4
gpt4 key购买 nike

我有一个包含 Listing、Tag 和 Listing_Tag 模型的应用程序。我想创建标签并在 Mechanize 任务中分配它们。目前我正在创建列表,遍历标签并创建它们,但是当我通过列表标签将标签分配给列表时,我收到此错误

rake aborted!
NoMethodError: undefined method `each' for 0:Integer
/Users/mycomp/RubymineProjects/OpportunityFinder/lib/tasks/brisbane.rake:181:in `block (2 levels) in <top (required)>'
/Users/mycomp/.rvm/gems/ruby-2.4.2/gems/nokogiri-1.8.4/lib/nokogiri/xml/node_set.rb:204:in `block in each'
/Users/mycomp/.rvm/gems/ruby-2.4.2/gems/nokogiri-1.8.4/lib/nokogiri/xml/node_set.rb:203:in `upto'
/Users/mycomp/.rvm/gems/ruby-2.4.2/gems/nokogiri-1.8.4/lib/nokogiri/xml/node_set.rb:203:in `each'
/Users/mycomp/RubymineProjects/OpportunityFinder/lib/tasks/brisbane.rake:170:in `block in <top (required)>'
/Users/mycomp/.rvm/gems/ruby-2.4.2@global/gems/rake-12.3.1/exe/rake:27:in `<top (required)>'
/Users/mycomp/.rvm/gems/ruby-2.4.2/bin/ruby_executable_hooks:15:in `eval'
/Users/mycomp/.rvm/gems/ruby-2.4.2/bin/ruby_executable_hooks:15:in `<main>'

第 170 行是 page.search,第 181 行是 t do 中的标签
class Listing < ApplicationRecord

has_many :listing_tags
has_many :tags, through: :listing_tags

class ListingTag < ApplicationRecord
belongs_to :listing
belongs_to :tag
end

class Tag < ApplicationRecord
has_many :listings, through: :listing_tags
end

在 Mechanize 中,我创建了一个列表和标签。
page.search('a[title="view business"]').each do |link|
mechanize.click(link)
l = Listing.find_or_create_by(name: mechanize.page.css('article h1[itemprop="name"]').text.strip)
t = mechanize.page.css('body main div.row.flex-page div.column.medium-3.__left-col-small article ul:nth-child(14) li').each do |tag|
Tag.find_or_create_by(name: tag.text.strip)
end

然后我想通过 Listing_tag 关联列表和标签
for tag in t do
ListingTag.find_or_create_by(listing_id: l.id, tag_id: tag.id)
end

我究竟做错了什么?我的连接表设置正确吗(我认为这是因为它在表单中有效)

最佳答案

看起来您想要执行以下操作:

ListingTag.find_or_create_by(listing_id: listing.id, tag_id: tag.id)

关于ruby-on-rails - Rails Mechanize 连接表循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51814854/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com