I am completely new to Rails and I have a database that links to a certain page depending on the user's search but it will always give me the id.
For example if a user searches, I will get, "localhost:3000/fruit/1" instead of "localhost:3000/fruit/apple". Does anyone know how to switch the url from an id to name?
You need to define a 'to_param' method in the model you are generating a link for, e.g.
class Fruit < ActiveRecord:Base
def to_param
name
end
end
Then in your controller you need to change the find for the show action to find by the attribute you are using in your 'to_param' method, e.g.
#fruit = Fruit.find_by(name: params[:id])
See http://api.rubyonrails.org/classes/ActiveRecord/Integration.html#method-i-to_param for additional details
Related
I'm wondering if it's possible to edit the default Rails routing convention to fetch a specific record based on a field that is not the ID?
For instance, instead of retrieving a specific record based on ID, with the verb/url combination:
GET /users/:id
Retrieve a specific record based on username, with the verb/url combination:
GET /users/:username
I don't see why this would be a problem theoretically, as long as usernames were required to be unique, but I'm having trouble understanding how to implement it based on the Rails Routing Guide.
I have gathered that I will need to add a line to my routes.rb file, to define a singular resource, just prior to:
resources :users
However, I'm having trouble understanding the syntax to accomplish this. Any help in understanding this would be greatly appreciated.
Yes it is possible and they are called Non Restful Routes in the rails documentation
A trivial example is doing the below in your routes.rb
get ':users/:show/:username', controller: "users", action: "show"
and in your UsersController you have a show action that looks like this:
def show
if params[:id].present?
#user = User.find(params[:id])
elsif params[:username].present?
#user = User.find_by(username: params[:username])
end
end
This way you support showing by id and username, if you want do disable support for either of them, modify the if clause as you wish
I think you are looking to change the to_param method like so:
class User < ActiveRecord::Base
def to_param
"#{id} #{name}".parameterize
end
end
This would give the url as: /user/id-name. If you want to get rid of the id before the name it gets a little more complicated. If you were just to remove it, it will more than likely break since ActiveRecord needs the id first for finds.
To get around this I would suggest using FriendlyId gem: https://github.com/norman/friendly_id
There is also a RailsCast showing how to use Friendly_id but its pretty straight forward.
The routes does not care if it is an ID or username.
It is really how you find it in the controller.
Just in the user show controller:
def show
#user = User.find_by_username params[:id]
end
I am building a small app, that allows users to create lists and within these lists they can add gifts that they want. So far its very similar to a ToDo list app.
I have three models:
User - Can have many Lists
List - Can have many gifts and belongs to User
Gift - Belongs to List
In my List model as well as storing the name of the list, Im also creating a unique string of letters and numbers and storing it as shared_key in the record. The code looks like this:
def create_unique_url
begin
self.shared_key = SecureRandom.urlsafe_base64(10)
end while self.class.exists?(shared_key: shared_key)
end
and ideally I want the url to look something like this app.com/public/long_string_shared_key_goes here
My main Question is, how should do I go about setting up a route to access the record at this public address.
Should I create another controller called public and have a show method there? Or should I create a public action in my llist controller and somehow manually create a route to it?
Since it's just a matter of single action I'd not suggest to redefine the #to_param, since it might affect all of your existing functionality. Still a matter of taste, mostly
routes:
resources :lists, except: [ :show ]
get '/public/:shared_key' => 'lists#show'
controller:
def show
#list = List.find_by(shared_key: params[:shared_key])
end
view:
link_to list.name, list_path(shared_key: list.shared_key)
In you case i would just alter a little the showing of the list. First in the list model redefine the to_param method
def to_param
long_string_shared_key_goes #by default this was returning the id - example...to access show a list you had to navigate to /lists/:id
end
Now you need to change the routes.rb
match 'public/:long_string_shared_key_goes', to :'lists#show', via: [:get]
Now you just have to change some find methods (if you are accessing the lists with example list.find(params[:id] you now have to take in consideration that you dont have the id in the params, but you long_string_shared_key).
Hope this answered your question.
Having some issues, I want my urls for the show action to be like:
/post/some-title
i.e. so wherever I reference the show_post_path tag (or whatever it is) it should make that url.
BUT, when editing/updating I want to do this using the ID of the post ie.
/post/234/edit
How can I achieve this, it seems what I am doing is messing things up because I used:
def to_param
#{title}"
end
In my post model.
I always add an attribute called 'slug' to posts and it acts as a slug for that post.
Then just find your posts with Post.find_by_slug(params[:id]).
You can even make it translatable.
Create a to_param method. For example:
def to_param
"#{self[:id]}-#{title.gsub(/[^a-z0-9]+/i, '-')}"
end
Assuming the field you wanted to be in the URL is title, then your posts' URLs would be like /posts/1-this-is-a-post.
In some book, it is recommended that to_param is changed to
class Story < ActiveRecord::Base
def to_param
"#{id}-#{name.gsub(/\W/, '-').downcase}"
end
end
so that the URL is
http://www.mysite.com/stories/1-css-technique-blog
instead of
http://www.mysite.com/stories/1
so that the URL is more search engine friendly.
So probably to_param() doesn't need to be used by other parts of Rails that changing it may have any side effect? Or maybe the only purpose is to construct a URL for linking?
Another thing is, won't it require to limit the URL size to be less than 2k in length -- will it choke IE if it is more than 2k or maybe the part more than 2k is just ignored by IE and so the URL still works. It might be better to be limited to 30 or 40 characters or something that will make the URL not exceedingly long.
Also, the ri doc of to_param:
class User < ActiveRecord::Base
def to_param # overridden
name
end
end
if to_param is changed like that, then the link actually won't work, as
http://www.mysite.com/stories/1-css-technique-blog
will work, but
http://www.mysite.com/stories/css-technique-blog
will not work as the ID is missing. Are there other ways to change the to_param method?
Update: on second thought, maybe
http://www.mysite.com/stories/css-technique-blog
won't work well if there are many webpages with similar title. but then
http://www.mysite.com/user/johnchan
will work. Will it be params[:id] being "johnchan"? So then we will use
user = User.find_by_login_name(params[:id])
to get the user. So it just depends on how we use the param on the URL.
C:\ror>ri ActiveRecord::Base#to_param
-------------------------------------------- ActiveRecord::Base#to_param
to_param()
------------------------------------------------------------------------
Returns a String, which Action Pack uses for constructing an URL to
this object. The default implementation returns this record's id as
a String, or nil if this record's unsaved.
For example, suppose that you have a User model, and that you have
a +map.resources :users+ route. Normally, +user_path+ will
construct a path with the user object's 'id' in it:
user = User.find_by_name('Phusion')
user_path(user) # => "/users/1"
You can override +to_param+ in your model to make +user_path+
construct a path using the user's name instead of the user's id:
class User < ActiveRecord::Base
def to_param # overridden
name
end
end
user = User.find_by_name('Phusion')
user_path(user) # => "/users/Phusion"
If you want to make your url more search engine friendly, you can use the friendly_id gem which makes exactly what you want. Is the easier way I've found to generate search engine friendly permalinks.
I am currently developing a blogging system with Ruby on Rails and want the user to define his "permalinks" for static pages or blog posts, meaning:
the user should be able to set the page name, eg. "test-article" (that should be available via /posts/test-article) - how would I realize this in the rails applications and the routing file?
for user-friendly permalinks you can use gem 'has_permalink'. For more details http://haspermalink.org
Modifying the to_param method in the Model indeed is required/convenient, like the others said already:
def to_param
pagename.parameterize
end
But in order to find the posts you also need to change the Controller, since the default Post.find methods searches for ID and not pagename. For the show action you'd need something like this:
def show
#post = Post.where(:pagename => params[:id]).first
end
Same goes for the other action methods.
You routing rules can stay the same as for regular routes with an ID number.
I personally prefer to do it this way:
Put the following in your Post model (stick it at the bottom before the closing 'end' tag)
def to_param
permalink
end
def permalink
"#{id}-#{title.parameterize}"
end
That's it. You don't need to change any of the find_by methods. This gives you URL's of the form "123-title-of-post".
You can use the friendly_id gem. There are no special controller changes required. Simple add an attribute for example slug to your model..for more details check out the github repo of the gem.
The #63 and #117 episodes of railscasts might help you. Also check out the resources there.
You should have seolink or permalink attribute in pages' or posts' objects. Then you'd just use to_param method for your post or page model that would return that attribute.
to_param method is used in *_path methods when you pass them an object.
So if your post has title "foo bar" and seolink "baz-quux", you define a to_param method in model like this:
def to_param
seolink
end
Then when you do something like post_path(#post) you'll get the /posts/baz-quux or any other relevant url that you have configured in config/routes.rb file (my example applies to resourceful urls). In the show action of your controller you'll just have to find_by_seolink instead of find[_by_id].