我遵循了Simply Rails 2中的教程,但我得到了NoMethodError
这是我的story.rb模型:
class Story < ApplicationRecord
validates :name, :link, presence: true
has_many :votes do
def latest
find :all, :order => 'id DECS', :limit => 3
end
end
end这是我的show.html.haml视图:
%h2
%span#vote_score
Score: #{@story.votes.size}
= @story.name
#vote_form
= form_for @story, method: "post", :url => story_votes_path(@story) do
= submit_tag 'shove it'
%ul#vote_history
- if @story.votes.empty?
%em No shoves yet!
- else
= render :partial => 'votes/vote', :collection => @story.votes.latest
%p
= link_to @story.link, @story.link完全错误描述:
undefined method `latest' for #<Vote::ActiveRecord_Associations_CollectionProxy:0x00007f4234aea9c0>
Did you mean? last
Extracted source (around line #15):
%em No shoves yet!
- else
= render :partial => 'votes/vote', :collection => @story.votes.latest ##this is line 15
%p
= link_to @story.link, @story.link
Rails.root: /home/kevin/shovell2有人能帮我解决这个问题吗?谢谢。
发布于 2020-04-04 18:59:48
您确定要将该块传递给has_many吗?我认为您想要的是在Vote模型中声明该latest方法,可能是一个作用域
scope :latest, -> { order('id DESC').limit(3) } 或者方法也是如此。
def self.latest
order('id DESC').limit(3)
end请注意您正在使用的rails版本:您正在创建模型的子类化ApplicationRecord,这存在于最新版本的rails中(可能是从rails 5开始)。另一方面,这种方法似乎来自rails的一个非常老的版本,可能是2 find :all, :order => 'id DECS', :limit => 3
发布于 2020-04-04 19:02:19
您需要将最新的内容添加到投票模型中,而不是添加到Story模型中。它可以像这样代替方法。
class Vote < ApplicationRecord
...
scope :latest, -> { order('id DESC').limit(3) }
...
endhttps://stackoverflow.com/questions/61027019
复制相似问题