【问题标题】:trouble associating tags with entries将标签与条目关联起来的麻烦
【发布时间】:2017-03-17 20:18:40
【问题描述】:

这个问题的基本前提是如何使标签链接工作,所以当你点击它时,它会出现与此相关的所有条目。

但是,当您单击链接时,基本上,不管其标题如何,都会显示一个空白页面。它不显示与其标签相关的条目。

很明显,该协会在某个地方不起作用?还是 Tags 控制器中的show 方法不对?不知道究竟要在这里解决什么问题。

到目前为止,这是我的代码:(与空白页有关的部分位于最底部)

条目控制器

class EntriesController < ApplicationController
  def index 
    @entries = Entry.all 
    @tags = Tag.all
  end

  def scrape
    RedditScraper.scrape

    respond_to do |format|
      format.html { redirect_to entries_url, notice: 'Entries were successfully scraped.' }
      format.json { entriesArray.to_json }
    end
  end
end

标签控制器

class TagsController < ApplicationController
  def index
    @tags = Tag.all 
  end
    
  def show 
    @tag = Tag.find(params[:id])
  end
end

入门模式

class Entry < ApplicationRecord
  has_many :taggings
  has_many :tags, through: :taggings

  validates :title, presence: true
  validates :link, presence: true

  def tag_list 
    tags.join(", ")
  end

  def tag_list=(tags_string)
    tag_names = tags_string.split(",").collect{|s| s.strip.downcase}.uniq
    new_or_found_tags = tag_names.collect { |name| Tag.find_or_create_by(name: name) }
    self.tags = new_or_found_tags
  end
end

标签模型

class Tag < ApplicationRecord
  has_many :taggings
  has_many :entries, through: :taggings

  validates :name, presence: true
end

标记模型

class Tagging < ApplicationRecord
  belongs_to :tag
  belongs_to :entry
end

条目 index.html.erb

<div class="container-fluid">
  <div class="row">
    <div class="col-md-8">
      <div class="card-columns">
        <% @entries.reverse.each do |entry| %>
          <div class="card">
            <div class="card-block">
              <p class="card-title"><b><%= entry.title %></b></p>
              <p class="card-text"><%= entry.link %></p>
            </div>
          </div>
       <% end %>
    </div>
  </div>
 
  <div class="col-md-4">
    <p>Tags: <% @tags.each do |tag| %>
      <%= link_to tag.name, tag_path(tag) %>
    <% end %>
  </div>
</div>

标签 show.html.erb(这部分不起作用 - 即与标签关联的条目 - 页面显示为空白)

<h1>Entries Tagged with <%= @tag.name %></h1>

<ul>
  <% @tag.entries.each do |entry| %>
    <li><%= link_to entry.title, entry_path(entry) %></li>
  <% end %>
</ul>

<%= link_to "All Tags", tags_path %>

Rails 控制台

e = Entry.first
  Entry Load (28.8ms)  SELECT  "entries".* FROM "entries" ORDER BY "entries"."id" ASC LIMIT $1  [["LIMIT", 1]]
=> #<Entry id: 4, title: "Sweet old man at the beach: \"Would you like me to ...", link: "/r/funny/comments/5zut3e/sweet_old_man_at_the_beac...", created_at: "2017-03-17 08:20:25", updated_at: "2017-03-17 08:20:25">
irb(main):036:0> t = Tag.first
  Tag Load (0.5ms)  SELECT  "tags".* FROM "tags" ORDER BY "tags"."id" ASC LIMIT $1  [["LIMIT", 1]]
=> #<Tag id: 3, name: "https://www.reddit.com/r/funny/", created_at: "2017-03-17 08:20:26", updated_at: "2017-03-17 08:20:26">
irb(main):037:0> tag.entries
NoMethodError: undefined method `entries' for nil:NilClass

Rails 控制台 2

irb(main):041:0> tag = Tag.first
  Tag Load (2.6ms)  SELECT  "tags".* FROM "tags" ORDER BY "tags"."id" ASC LIMIT $1  [["LIMIT", 1]]
=> #<Tag id: 3, name: "https://www.reddit.com/r/funny/", created_at: "2017-03-17 08:20:26", updated_at: "2017-03-17 08:20:26">
irb(main):042:0> tag.entries << Entry.first
  Entry Load (0.8ms)  SELECT  "entries".* FROM "entries" ORDER BY "entries"."id" ASC LIMIT $1  [["LIMIT", 1]]
   (32.6ms)  SAVEPOINT active_record_1
  SQL (318.8ms)  INSERT INTO "taggings" ("tag_id", "entry_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id"  [["tag_id", 3], ["entry_id", 4], ["created_at", 2017-03-18 05:05:24 UTC], ["updated_at", 2017-03-18 05:05:24 UTC]]
   (0.3ms)  RELEASE SAVEPOINT active_record_1
  Entry Load (1.3ms)  SELECT "entries".* FROM "entries" INNER JOIN "taggings" ON "entries"."id" = "taggings"."entry_id" WHERE "taggings"."tag_id" = $1  [["tag_id", 3]]
=> #<ActiveRecord::Associations::CollectionProxy [#<Entry id: 4, title: "Sweet old man at the beach: \"Would you like me to ...", link: "/r/funny/comments/5zut3e/sweet_old_man_at_the_beac...", created_at: "2017-03-17 08:20:25", updated_at: "2017-03-17 08:20:25">]>
irb(main):043:0> tag.save
   (0.4ms)  SAVEPOINT active_record_1
   (0.3ms)  RELEASE SAVEPOINT active_record_1
=> true
irb(main):044:0> Tag.first.entries
  Tag Load (0.8ms)  SELECT  "tags".* FROM "tags" ORDER BY "tags"."id" ASC LIMIT $1  [["LIMIT", 1]]
  Entry Load (1.1ms)  SELECT "entries".* FROM "entries" INNER JOIN "taggings" ON "entries"."id" = "taggings"."entry_id" WHERE "taggings"."tag_id" = $1  [["tag_id", 3]]
=> #<ActiveRecord::Associations::CollectionProxy [#<Entry id: 4, title: "Sweet old man at the beach: \"Would you like me to ...", link: "/r/funny/comments/5zut3e/sweet_old_man_at_the_beac...", created_at: "2017-03-17 08:20:25", updated_at: "2017-03-17 08:20:25">]>
irb(main):045:0> 

rails 爬虫代码

需要'open-uri'

模块 RedditScraper

def self.scrape doc = Nokogiri::HTML(open("https://www.reddit.com/"))

entries = doc.css('.entry')
entries.each do |entry|
  title = entry.css('p.title > a').text
  link = entry.css('p.title > a')[0]['href']
  name = entry.css('p.tagline > a.subreddit')[0]['href']
  Entry.create!(title: title, link: link)
  Tag.create!(name: name)

end

结束

结束

【问题讨论】:

  • 有什么问题?你遇到什么了?在没有狭窄范围的情况下,“不知道如何 X”对于 StackOverflow 来说不是一个很好的问题。
  • @coreyward,是的,我知道。抱歉有点啰嗦。让我稍微澄清一下问题的顶部......让我知道它是否需要进一步调整。
  • @coreyward,嘿,如果这样更好,请告诉我?谢谢。顺便说一句,圣帕特里克节快乐!
  • 您是否设置了标签和条目?当您执行rails console 时,您可以执行tag = Tag.first,然后当您执行tag.entries 时,您会在控制台中看到条目?
  • @SteveTurczyn,当我做tag = Tag.first 时,我得到了第一个条目。当我做tag.entries 时,我得到NoMethodError: undefined method 'entries' for nil:NilClass

标签: ruby-on-rails ruby


【解决方案1】:

更改您的爬虫代码以建立关联。

而不是...

  Entry.create!(title: title, link: link)
  Tag.create!(name: name)

做...

  entry = Entry.create!(title: title, link: link)
  tag = Tag.create!(name: name)
  tag.entries << entry
  tag.save!

【讨论】:

  • @SteveTurxzyn,如果它是一个典型的 ROR 项目而不是废弃的项目,你介意还包括传统的表演动作吗?也许这可以解决它?那么关联可以在上面Tag的show action中呢?想法?
  • 嗨,对不起,编辑了我的答案。我最初是为一对一编写的,但当然是多对多
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多