尝试创建“标签”时未定义的方法“map”

时间:2017-12-12 13:45:03

标签: ruby-on-rails ruby model tags

我正在重新使用本指南https://rubyplus.com/articles/4241-Tagging-from-Scratch-in-Rails-5,以便让'tastingsnotes'作为'roast.rb'模型上的标签。

但是,在尝试在浏览器中显示记录时,我收到错误var jobs = urls .Select(url => CreateBroswerJob(url)) .ToList(); 。我很确定这不是我不能以某种方式正确映射标签。我可以看到当我尝试编辑记录时,我在那里有标记。

逻辑是我有一个名为'Roasts'的模型我希望用户能够添加以逗号分隔的品酒笔记列表。因此,我将这些视为标签。

roast.rb

undefined method 'map'

note.rb

class Roast < ApplicationRecord
  has_many :tastings
  has_many :notes, through: :tastings

  def self.tagged_with(name)
    Note.find_by!(name: name).roasts
  end

  def self.note_counts
    Note.select('notes.*, count(tastings.note_id) as count').joins(:tastings).group('tastings.note_id')
  end

  def tastingnotes
    notes.map(&:name).join(', ')
  end

  def tastingnotes=(names)
    self.notes = names.split(',').map do |n|
      Note.where(name: n.strip).first_or_create!
    end
  end
end

tasting.rb

class Note < ApplicationRecord
  has_many :tastings
  has_many :roasts, through: :tastings
end

烤/ _form.html.rb

class Tasting < ApplicationRecord
  belongs_to :note
  belongs_to :roast
end

烤/ show.html.rb

//items not pasted for brevity
      <div class="form-group">
        <%= form.label :tastingnotes, "Notes (separated by commas)", class: 'control-label' %><br  />
        <%= form.text_area :tastingnotes, id: :roast_tastingnotes, class: "form-control" %>
      </div>
//items not pasted for brevity

控制台错误:

//items not pasted for brevity
<p>
  <strong>Tasting Notes</strong>
  <%= raw @roast.tastingnotes.map(&:name).map { |t| link_to t, tastingnotes_path(t) }.join(', ') %>
</p>
//items not pasted for brevity

2 个答案:

答案 0 :(得分:2)

你做了

 def tastingnotes
    notes.map(&:name).join(', ')
  end

返回逗号的字符串,如“choco,beer”

现在你确实映射到下面的字符串

<%= raw @roast.tastingnotes.map(&:name).map { |t| link_to t, tastingnotes_path(t) }.join(', ') %>

你可以尝试

  def tastingnotes
    notes.pluck(:name)
  end

<%= raw @roast.tastingnotes.map { |t| link_to t, tastingnotes_path(t) } %>

答案 1 :(得分:1)