ruby-on-rails - 尝试创建 'map' 时未定义方法 'tags'

标签 ruby-on-rails ruby model tags

我正在重新利用本指南 https://rubyplus.com/articles/4241-Tagging-from-Scratch-in-Rails-5允许我将“tastingsnotes”作为“roast.rb”模型上的标签。

但是,当我尝试在浏览器中显示记录时,出现错误 undefined method 'map'。我相当确定这归因于我没有以某种方式正确映射标签。当我尝试编辑记录时,我可以看到那里有标签。

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

烤.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

note.rb

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

tasting.rb

class Tasting < ApplicationRecord
  belongs_to :note
  belongs_to :roast
end

烤肉/_form.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

roasts/show.html.rb

//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

控制台错误:

Completed 500 Internal Server Error in 18ms (ActiveRecord: 1.1ms)



ActionView::Template::Error (undefined method `map' for "chocolate, citrus":String
Did you mean?  tap):
    39:
    40: <p>
    41:   <strong>Tasting Notes</strong>
    42:   <%= raw @roast.tastingnotes.map(&:name).map { |t| link_to t, tastingnotes_path(t) }.join(', ') %>
    43: </p>
    44:
    45:

最佳答案

你做到了

 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) } %>

关于ruby-on-rails - 尝试创建 'map' 时未定义方法 'tags',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47774187/

相关文章:

ruby-on-rails - docker-compose构建错误-不支持的版本

mysql - Rails、SQL 两列都匹配 !=

ruby-on-rails - 如何将 'select one...' 添加到 options_from_collection_for_select

ruby-on-rails - Neo4j.rb 创建独特的关系

javascript - 如何以编程方式处理英文缩写 [Regex, JS, Ruby]

typescript - 导出模型并在模板上使用

ruby-on-rails - 预先加载 "second degree"关联对象时出现问题

ruby - Sinatra 和 Grape API 在一起?

asp.net-mvc - MVC 多个 ViewModel 和 ModelState

perl - 奥莱特 : Unicode-question