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

标签 ruby-on-rails mechanize jointable

我有一个包含 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/

相关文章:

ruby-on-rails - 在 Rails 中使用 Javan-whenever 时如何让 cron 工作

ruby-on-rails - 这行代码 "expect { |b| 5.tap(&b) }.to yield_control"在功能上实现了什么?

ruby-on-rails - 显示相似用户

javascript - 如何单击具有 javascript :__doPostBack in href? 的链接

javascript - 在 Python 中使用 Mechanize 在标签内的输入中输入用户名

python - 将 Mechanize 与不在表单内的选择字段一起使用?

Hibernate:如何在 Annotation 中将三个 3 表连接到一个连接表中?

html - 如果样式设置为样式 ="display:none",是否可以通过网络抓取网站

mysql使用组从一个表中计算行并从第二个表中加入

php - 内部连接数据库