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.
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!
Building a simple phone book app and have a concern regarding the following:
Each of my listed contacts has a number resource, and their relationship is defined in the routes file as follows:
config/routes.rb
resources :contacts do
resources :numbers
end
In my webapp thus far, I have it so that a user can create a contact and then create a number corresponding with that contact. I list the numbers for the contact, and when the user clicks on it (in order to route to the numbers#show page for that specific number, I get the following error:
NoMethodError in NumbersController#show
undefined method `numbers' for nil:NilClass
I've had this error a ton of times, and always it happened because the contact wasn't instantiated properly. But in my code, everything is being saved to db properly as per my rails console exploration. Below is the code throwing the error, found inside my numbers controller:
def set_number #to do item
#number = #contact.numbers.find(params[:id])
end
And the parameters being passed in, according to the error page, are the following:
Parameters:
{"contact_id"=>"1",
"id"=>"1"}
I set #contact via this method in the numbers controller:
def set_contact
#contact = Contact.find(params[:contact_id])
end
and I call it at the top as so:
before_action :set_contact
Given that there are parameters, and Rails console tells me both the contact and the number were saved properly, any idea what's wrong?
As I posted as a comment:
You have to have your before_action :set_contact before your before_action :set_number, otherwise you won't have the #contact when calling the :set_number.
All the before_action runs in the order that you added them :)
Cheers
Clearly the error seems to be in set_number method inside your controller. And the reason is #contact is nil.
So, as in above comments, your set_contact method may be running after set_number
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.
Checks_controller
class Checkscontroller < ApplicationController
def show
#check= Tester.find(params[:id])
end
def new
end
def create
#check = Tester.new(check_params)
#check.save
redirect_to #check
end
def check_params
params.require(:check).permit(:title, :description)
end
end
I am trying to save the data in 'checks' controller to 'Tester' model, getting "NoMethodError in ChecksController#create", undefined method tester_url' for#` while trying to save the data to my DB. There seems to be some issue on this line: "redirect_to #check".
Routes.rb
Rails.application.routes.draw do
get 'home/screen'
resources :checks
root 'home#screen'
end
EDIT: I see this answer got accepted. To anyone else looking at this: PLEASE DO NOT DO THIS WITHOUT A REALLY GOOD REASON.
Ok, so since you want to use the ChecksController for your Tester model, you'll have to add this to your routes: note that I'm assuming that you do not have a Check model, since I don't see it anywhere and youre using Tester as a check?
resources :testers, as: 'checks' controller: 'checks'
This line will make it so that /checks/1 goes to a Tester object with ID: 1, and use the ChecksController show method to show it
Old answer, for posterity
You're getting this error because you're missing routes for your Tester model in your routes.rb file.
You could add resources :testers to it and it will work. Of course you also already need AT LEAST your TestersController to exist with a show action
This error is occurring because when you redirect_to #check, Rails knows it's a Tester object and expects a route called tester to route to TestersController#show. It's attempting to use a helper method that rails creates for routes, called tester_url
I'm new to Ruby and Rails, coming from Java and Playframework.
I'm following a tutorial http://www.sitepoint.com/building-your-first-rails-application-views-and-controllers/
I am getting an error on the line #shortened_url = Url.new
The error is :
NameError in UrlsController#new
uninitialized constant UrlsController::Url
I feel this is something like a ClassNotFoundError in Java ?? not sure ... does anyone know what I have to do. Is it basically a matter of using include or require, with the correct reference.
Apologies for the total newb question but I find it much easier to learn by doing and making mistakes, it sticks - and I reckon others will benefit too.
class UrlsController < ApplicationController
def new
#shortened_url = Url.new
end
def create
#shortened_url = Url.new(params[:url])
if #shortened_url.save
flash[:shortened_id] = #shortened_url.id
redirect_to new_url_url
else
render :action => "new"
end
end
def show
#shortened_url = Url.find(params[:id])
redirect_to #shortened_url.url
end
end
May or may not be the issue you're having, but Url is a reserved word in Rails.
Source: http://bparanj.blogspot.co.uk/2011/07/reserved-words-in-rails.html
Alternatively, it's weird that calling Url.new is calling new on your UrlsController instead of the Url model. This backs up my idea about using reserved words, it can often cause strange behaviour.
Edit: Oh and it looks like from another comment that you don't have a Url model. You'll need one of those before you can called .new on it. That said, don't create a model called Url, the reserved word thing will probably come back to bite you.