1
我有一個控制器稱爲博客:未定義的方法 - 導軌
class BloggerController < ApplicationController
def home
end
def favoritePosts
@blogger = current_blogger
@favorites = @blogger.favorite_posts
end
def suggestedPosts
posts = Post.all
@suggestedPosts = posts.similar_posts
end
end
而在Blogger的模型我有一個方法:
def similar_posts
title_keywords = Post.body.split(' ')
Post.all.sort do |post1, post2|
post1_title_intersection = post2.body.split(' ') & title_keywords
post2_title_intersection = post2.body.split(' ') & title_keywords
post2_title_intersection.length <=> post1_title_intersection.length
end
end
當我運行服務器的給我一個錯誤:
undefined method `similar_posts' for #<Post::ActiveRecord_Relation:0x007fa365029760>
計算器上搜索後,我試圖def self.similar_posts
但它仍然給出了同樣的錯誤消息。我也試過new
這個控制器,就像@suggestedPosts = posts.new.similar_posts
這樣仍然給我相同的錯誤。 有關如何解決這個問題的任何建議?
問題是您在Post上使用Blogger.Method,Post中沒有這種方法。嘗試在Post上定義 – Boltz0r
'similar_posts'在'post'對象上定義,而不是'posts',所以'@suggestedDevelopers = posts.map(&:similar_posts)' –
您試圖調用'similar_posts'方法對象數組。請嘗試'posts.first.similar_posts' –