NoMethodError in Valuations#show
undefined method `each' for #<Valuation:0x007fb6e9a62c08>
Line: <% @valuation.each do |valuation| %>
我们应该如何在控制器中定义它,以便用户能够&#34;喜欢&#34;显示页面中的估价值?
控制器
def show
@valuation = Valuation.find(params[:id])
@commentable = @valuation
@comments = @commentable.comments
@comment = Comment.new
end
def like
@valuation = Valuation.find(params[:id])
@valuation_like = current_user.valuation_likes.build(valuation: @valuation)
if @valuation_like.save
@valuation.increment!(:likes)
flash[:success] = 'Thanks for liking!'
else
flash[:error] = 'Two many likes'
end
redirect_to(:back)
end
喜欢显示:
<% @valuation.each do |valuation| %>
<%= pluralize(valuation.likes, 'like') %>
<%= link_to content_tag(:span, '', class: 'glyphicon glyphicon-thumbs-up') +
' Like it', like_valuation_path(:id => valuation.id), method: :post %>
<% valuation.likers.each do |user| %>
<%= user.name %>
<% end %>
<% end %>
有估值和valu_like 模型。
class ValuationLike < ActiveRecord::Base
belongs_to :valuation
belongs_to :user
validates :user, uniqueness: { scope: :valuation }
belongs_to :liker, class_name: 'User', foreign_key: :user_id
belongs_to :liked_comment, class_name: 'Valuation', foreign_key: :valuation_id
end
class Valuation < ActiveRecord::Base
has_many :valuation_likes
has_many :likers, through: :valuation_likes, class_name: 'User', source: :liker
end
答案 0 :(得分:1)
您正在尝试迭代单个项目,find
方法返回1 Valuation
个对象,或者在找不到它时抛出:
@valuation = Valuation.find(params[:id])
所以当你尝试这样做时:
<% @valuation.each do |valuation| %>
解释器生气,单Valuation
没有each
方法,因为此警告告诉您:
undefined method `each' for #<Valuation:0x007fb6e9a62c08>
因此,不要迭代@valuation
对象,只需使用它:
<%= pluralize(@valuation.likes, 'like') %>
<%= link_to content_tag(:span, '', class: 'glyphicon glyphicon-thumbs-up') +
' Like it', like_valuation_path(:id => @valuation.id), method: :post %>
<% @valuation.likers.each do |user| %>
<%= user.name %>
<% end %>
你可以避免在你的观点中使用content_tag
(这更像是帮助者)。 link_to
函数可以对其内容进行处理,因此请尝试以下方法:
<%= pluralize(@valuation.likes, 'like') %>
<%= link_to like_valuation_path(:id => @valuation.id), method: :post do %>
<span class='glyphicon glyphicon-thumbs-up'></span> Like it
<% end %>
<% @valuation.likers.each do |user| %>
<%= user.name %>
<% end %>