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?
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.
Related
I'm trying to get a variable from the controller over to the model. Its the value of a checkbox passed up from the View. I cant see it in the controller (0 or 1) and just need to get it to the model. I have seen tons of examples on here but none of them seem to work for me. Maybe its something about the Ruby environment we have setup? Its a Rails 5 environment.
Here is what I have tried so far and the errors it gives in the logs:
Controller:
#vin = Vehicle.create!
#results = #vin.myvin!(params[:vehicle][:vincheck])
Model:
def myvin!(localvin)
logger.info "MADE IT INTO VIN"
end
Error in development.log:
AbstractController::DoubleRenderError (Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and at most once per action.
I'm not calling render or redirect!! Just trying to call the method in the model.
I have also tried a variation like:
Controller:
Vehicle.myvin(params[:vehicle][:vincheck])
Model:
def self.myvin(localvin)
logger.info "MADE IT INTO VIN"
end
But regardless... I always get that render error in the logs!
I have tried instantiating a new object:
Controller:
Vehicle.new(params[:vehicle][:vincheck])
Model:
attr_reader :localvin
def initialize(localvin)
logger.info "MADE IT INTO VIN"
end
When I do that I get:
500wrong number of arguments (given 0, expected 1)
Short Stack
app/models/vehicle.rb:25:in 'initialize'
app/controllers/vehicles_controller.rb:84:in 'new'
Anyone have any thoughts on how I can get this data over? Maybe it has something to do with the Vehicle Model itself? In the controller it gets instantiated at different places.
For example:
def index
#vehicles = Vehicle.active
end
def create
#this is where I am putting all my code
#not really sure how this is getting created since there was no
#initialize in the code before I added one
#vehicle = Vehicle.new(vehicle_params.merge(
created_by_id: current_user.id,
created_by_name: current_user.name,
deleted: false))
end
thanks!
I have 3 scaffolds that resources are nested as following: mangas > chapters > scans. I'm trying to create a website that allows visitors to read mangas chapters, but I'm getting some difficulties to set up the scan_controller's setter.
I have some constraints to follow: the manga scaffold uses FriendlyId, and both chapters and scans are shown to the URL via their chapter/scan number (an integer)
So, for the manga controller, i did the following:
private
def set_manga
#manga = Manga.friendly.find(params[:id])
end
I simply followed the manuel, no problem whatsoever.
For the chapter_controller, I did this
private
def set_chapter
#manga = Manga.find_by(slug: params[:manga_id])
#chapter = #manga.chapters.find_by(chapter_number: params[:id])
end
This allows me to get all chapters that are linked to the manga I want, and only them. Plus, I get to pass the chapter_number as an id into the link.
And, lastly, I tried this for the scan_controller:
private
def set_scan
#manga = Manga.find_by(slug: params[:manga_id])
#chapter = #manga.chapters.find_by(chapter_number: params[:id])
#scan = #manga.chapters.scans.find(params[:id])
end
However, at this point, I can't get a satisfying result. With this configuration, I get undefined method 'pejis' for #<Chapter::ActiveRecord_Associations_CollectionProxy:0x0000000713d1a0>. I tried to also set as follow:
private
def set_scan
#chapter = Chapter.find_by(chapter_number: params[:id])
#scan = #chapter.scans.find_by(scan_number: params[:id])
end
But i get undefined method 'pejis' for nil:NilClass, which is weird because it doesn't return any error with predefined ids in the rails console.
As anyone an idea ?
Thank you in advance
So, after re-reading again and again my code, I simply needed to do the following:
def set_peji
#chapter = Chapter.find_by(chapter_number: params[:chapter_id])
#peji = #chapter.pejis.find_by(scan_number: params[:id])
end
So I had to remove #manga since it's not concerned anymore, then to set the scan's chapter_id as being the chapter's number.
I have a routes like this :
get ':user_name', to: 'profile#show', as: :profile
And the show method looks like this
before_action :set_user
def show
#posts = #user.posts.order('created_at DESC')
end
def set_user
#user = User.find_by(user_name: params[:user_name])
end
Everything seems fine . Like
If i go to localhost/hello its works.
But if i go to localhost/hello.world it gives error and says that undefined method posts for nil:NilClass And it also says
Parameters:
{"user_name"=>"hello",
"format"=>"world"}
But we know user_name should be hello.world
Then why is this error ?? :(
Clearly I think this line is creating problem
#user = User.find_by(user_name: params[:user_name])
How to fix it :( really annoying problem :(
This is a combination of two problems:
You are using find_by instead of find_by!. The normal version won't raise an ActiveRecord::RecordNotFoundException when it can't find the record, which would gracefully make rails respond with a 404 and aport the before_action, which means #user ends up set to nil, and so you can't call .posts on it.
As #davidwessman has pointed out in the comments, you can't use dots by default on Rails routes. I suspect you have a record with name hello.world, but it's trying to find just hello and so it can't find anything.
I'm trying to include a few other recent articles when someone views a particular article in my Rails app.
I have the following method in my controller:
def show
#article = Article.find(params[:id])
#recents = Article.where(!#article).order("created_at DESC").limit(4).offset(1)
end
As the expert eye might see, #recents isn't correct. It's my best guess. :)
How do I show some recent articles but not repeat the one they are currently viewing?
You should use a scope in the model, for it has a lot of advanteges. Learn about scopes here. Your case should be something like this:
In the model:
class Article < ActiveRecord::Base
scope :recent, ->(article_id) { where.not(id: article_id).order(created_at: :desc).limit(4) }
end
and in the controller:
def show
#article = Article.find(params[:id])
#recent = Article.recent(#article.id)
end
This way the recent scope will always get the four last articles leaving out the article you pass in as an argument. And scopes are chainable so you could do something like this as well:
def some_action
#user = User.find(params[:user_id])
#user_recent_articles = #user.articles.recent(0)
end
You are getting the user recent articles. I pass a zero because the scope asks for an argument. You could create a different scope if you want to do it the cleanest way.
This, assuming a user has_many articles.
Well, hope it helps!
try with #recents = Article.where.not(id: #article.id).order("created_at DESC").limit(4)
click here - section 2.4 :).
I think there is a way of only making one call instead of 2 the way you have it now.
With the koala gem I am trying to count checkins for a page. I am using rails.
In my user.rb I have a method for getting a new connection to the Facebook graph:
class User < ActiveRecord::Base
def facebook
#facebook ||= Koala::Facebook::API.new(oauth_token)
end
end
In my school.rb I have a method for counting the checkins:
class school < ActiveRecord::Base
def count_checkins(name)
checkins = #facebook.fql_query("SELECT checkins FROM page WHERE name = #{name}")
end
end
And I am calling it from the view like this:
<%= #school.count_checkins(#school.name) %>
But I get the following error:
undefined method `fql_query' for nil:NilClass
Dont really understand why I get this error, any help would be wonderful.
It looks like you haven't actually created the #facebook object inside your School model. We'd need to see the rest of your school.rb file to know for sure. I'd suggest you create the object inside your School.initialize() method like so:
def initialize(oauth_token)
unless oauth_token.nil?
#facebook = Koala::facebook::API.new(oauth_token)
end
end
In order for this to work, you'll need to pass the desired oauth_token to your School.new() call. Then you'll have one #facebook object for each School.
Edit
After looking at the gist, I realized that you had actually intantiated a User object, and called the facebook method on that. That is actually the better way to do it. The problem is, you're using #current_user, which would have to be setup as a property of the school model. You probably meant to use the helper function current_user instead.
def count_checkins(name)
u = current_user
u.#facebook.fql_query("SELECT checkins FROM page WHERE name = #{name}")
end
Try that and see what happens. At the very least, you should get a different error message.
Edit 2
So, now I'm thinking the current_user function should be called in controller code, not model code. This is because the current user is something that doesn't really exist except as part of an active request. Therefore, we should take User u as a parameter to the count_checkins function like so:
def count_checkins(name, u)
u.facebook.fql_query("SELECT checkins FROM page WHERE name = #{name}")
end
You'll need to change the code where you call count_checkins() too:
count_checkins(name, current_user)
That should do it. Let's see!