Gurmukh Singh
Gurmukh Singh

Reputation: 2017

Undefined method in controller - rails

I have a controller called blogger:

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

And in the Blogger model i have a method:

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

When i run the server its gives me an error:

undefined method `similar_posts' for #<Post::ActiveRecord_Relation:0x007fa365029760>

After searching on stackoverflow i tried def self.similar_postsbut it still gives the same error message. I also tried new in the controller like this @suggestedPosts = posts.new.similar_posts which still gives me the same error. Any suggestions on how to overcome this?

Upvotes: 1

Views: 885

Answers (1)

Michael Gaskill
Michael Gaskill

Reputation: 8042

You have 2 issues happening at the same time. The first is that you're using posts in your call, when you should be using something more like post.blogger. The specific object depends on what your intent actually is.

The second issue is that you're making the call to similar_posts on the association, not on an individual record. This can be resolved with a call to each on the association.

So, putting those together and looking at what you might have meant, I think that you might have intended this as your suggestedPosts method:

def suggestedPosts
  posts = Post.all
  @suggestedPosts = posts.map {|post| post.blogger.similar_posts }
end

I also changed the name of @suggestedDevelopers to @suggestedPosts, because I don't think that you meant 'developers' in this case. This should give you something closer to what it appear you were trying for.

Upvotes: 1

Related Questions