Been trying to get this working for the past several hours, I'm probably over looking something quite simple. Basically I have a "posts" model, and one of the columns I have created is named guid
, which is just a user definable field that gets saved to the database.
I'm looking to find_by
the guid
instead of the default id
.
Of course I've tried @post = Post.find_by_guid(params[:guid])
in my posts controller show
action, but when I attempt to call it from the url (ex: mysite/post/53), in the server console it says guid is NULL
Webrick Console:
Processing by PostsController#show as HTML
Parameters: {"id"=>"53"}
Post Load (0.4ms) SELECT "posts".* FROM "posts" WHERE "posts"."guid" IS NULL LIMIT 1
....
if the route is
get "/posts/:id"
Then you will its the id that is going to be placed in the params which you can see in the output. So use params[:id]
@post = Post.find(params[:id])
You should change your route if you are passing a GUID :
get "posts/:guid" ...
Hit the url "posts/21EC2020-3AEA-1069-A2DD-08002B30309D"
And then in the controller:
@post = Post.find_by guid: params[:guid]
Rails passes instance variables (any variable starting with @) set in the controller to the views. Referencing instance variables in the view that the controller did not set will return nil, which does not have any of the methods you are going to call on it, hence the "No method" errors.
Any time you run into trouble, check your assumptions at the console. I recommend using Pry . Using Pry (calling "binding.pry" in your code) you can actually stop the execution at any point and look around. That way you never have to guess.
The find_by_[column]
method is deprecated.
Use the following syntax: find_by guid: params[:guid]
Your parameters hash does not contain a :guid
key. If you were to use mysite/post/53?guid=SOMETHING
then you will see a :guid
key in params
.
Do you want the 53 in this example to be the GUID parameter? There are ways to change the Rails routes to get that parameter to be guid
instead of id
, but if 53 is the GUID, you can always go:
Post.find(:guid => params[:id]).first
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.