How do rails extract an id from an instance variable? - ruby-on-rails

I'm reading "Rails Routing from the Outside In" on RailsGuides.
In Section 1.2, it says
<%= link_to 'Patient Record', patient_path(#patient) %>
will generate the path /patients/17.
What I'd like to know is how rails extract the id from the instance variable.
I've been trying to find the corresponding line of the code on GitHub but can't find.

The ID comes from calling #to_param on the object. Here is a little documentation about it, http://guides.rubyonrails.org/active_support_core_extensions.html#to-param

It calls a to_param method which by default will produce the ID. You can override it to produce nice URLs like this
class Post < ActiveRecord::Base
def to_param
"#{id}-#{title}"
end
end

method responsible is to_param. link to line on
github

Related

is this the right link_to rails syntax?

<%= link_to "Profile", #user %>
# => Profile
if i use the above code replacing "Profile" with "Category" and #user with #category/#subcategory what do I then point the html link a href etc to?
Check the documentation for this method here.
The first parameter of the link_to method is the displayed text.
Secondly, you can pass in a single instance of an object which will generate a link to the objects #show action.
You may however pass a link explicitly (most common in my opinion).
This can be done by using the Rails path-helpers (user_path(#user)) or by passing in a string.
In your example, if you exchange #user with #category it would link to the categories #show action instead (Assuming you have a Category model and #category isn't nil.
Again, have a look at the documentation of the link_to method and get familiar with it.

Why ruby on rails link_to redirect to itself?

Lets say I have a controler test.
In test I define 3 actions:
def zah
end
def zeh
end
def zih
end
I have the views:
zah.html.erb
zeh.html.erb
zih.html.erb
and under routes.rb I have:
get 'test/zah'
get 'test/zeh'
get 'test/zih'
If I write under zah.html.erb, using code automaticaly created from rubymine IDE, this:
<%= link_to test_zeh_path%>
I will get my page source code with this:
http://localhost:3000/test/zeh
which makes the redirection from zah be itself.
running rake routes returns this:
Prefix Verb URI Pattern Controller#Action
test_zah GET /test/zah(.:format) test#zah
test_zeh GET /test/zeh(.:format) test#zeh
test_zih GET /test/zih(.:format) test#zih
Can anyone explain to me why is the link going to itself (from zah to zah) instead of another page(from zah to zeh)?
Edit:
I have found out that adding a name to a link makes the generated code works right:
<%= link_to 'zeh', test_zeh_path%>
I have seen the first usage (link_to test_zeh_path) here at 22:45.
Ruby on rails api does says that if nil name is passed then "the value of the link itself will become the name.".
As for a mistake of myself I was wondering why Dave Jones was able to create a link without a name, but he wasnt and that can be seen on his source code.
Because you have written the url in the display part.
You can simply do
<%= link_to 'Goto Zeh', test_zeh_path %>
and you will be good to go.

How to use "impressionist" gem in Rails?

I am new to rails dev and is looking to use https://github.com/charlotte-ruby/impressionist but not able to figure out how to use it looking at its documentation. I have done the migration and when trying to put
class ArticlesController < InheritedResources::Base
impressionist
end
OR
class ArticlesController < InheritedResources::Base
impressionist :actions=>[:show,:index]
end
it is throwing no method found error. I am unsure which code needs to be put in model, which to be in controller and which to be in views to see view_count, any help ?
the first question was a type
and as for your second question (inside the comment) the easiest but very efficient way would be
in the view:
<% #pages.each do |page| %>
<%= page.impressionist_count %>
<% end %>
You can also use Impression as a model to query stuff, just like normal models. For example,
Impression.where(user_id: 12).length
I find this is handy if you need some advanced queries.
The documentation does not specify to re-start server. This is not obvious as it does not apply to all gems, however it is required for impressionist.

Rails: Proper way to add functionality to rails methods

I'm just starting to tinker with extending the rails framework, and as an experiment, I thought I'd add some extra info inside the form_for helper. Specifically, when form_for is called, I'd like to generate an extra h1 tag such as:
# regular form_for <form> opening tag
<h1>Woohoo! It's added!</h1>
# tags fed into form_for via &proc
# form_for close <form> tag
At the moment I've added a /lib file that opens up ActiveRecord::FormHelper and overrides "form for". Needless to say writing out the whole form_for method with just the one added line added is dog ugly...but I can't call super() because, well, instead of inheriting from the method I'd like to super(), I've just overwritten it in /lib.
So, assuming I stubbornly want the functionality to be called via the same form_for tag (instead of, for example extended_form_for), what's the standard way for calling back to the original form_for method I'm overwriting? alias_method_chain? Thought I'd ask before I cement in some potentially lousy practices. If any hardened veterans could give an example I'd be appreciative.
Cheers
You could override form_for in your ApplicationHelper:
module ApplicationHelper
def form_for(*)
content_tag(:h1, "Woohoo! It's added!") + super
end
end
alias_method_chain is by far the simplest way to overwrite the method while still being able to call the original method. So in your lib file you'll want something like this:
def form_for_with_header(...)
form_for_without_header(...)
content_tag(:h1, "Header tag here")
# etc...
end

Correct method for custom Rails routing

In my routes I currently have resources :users and so I get the routes such as /users/id/ and /users/id/edit and so on...however, I am wanting to have the 'default' URLs for my pages begin with /name where name is the user's unique login name.
So, right now my routes file looks like this.
resources :users
match '/:name' => 'users#show_by_name'
Then in my users_controller.rb file, I have methods defined as such...
def show_by_name
#user = User.find_by_name(params[:name])
render 'show'
end
So, basically it is doing the same thing as def show but instead of an id being passed in the URL, it's a name.
In my views I am linking like this...
<li><%= link_to "My Profile", "/#{current_user.name}" %></li>
As opposed to using <li><%= link_to "My Profile", current_user %></li>
I am wondering if I am going about this the correct way. I feel like I am doing something unnecessary by using extra methods in my users_controller.
Would I be better off just removing the resources :users line and creating my own routes that are more suited towards the type of URLs I want on my application?
Thanks for your time.
You might be better off overriding the to_param method in your User model. Rails has in built function for search friendly URL's
class User < ActiveRecord::Base
def to_param
"#{user.name}"
end
end
Url's will generate as
user_url(#user)
#http://0.0.0.0:3000/users/andrew
# Controller
#user = User.find_by_name(params[:id])
I would advice you to use FriendlyID, it's a neat gem that translates the :id to a value based on one of the table's columns. This could be a title for instance or name in your case.
I found it fairly easy to start using.
Ryan Bates talks about it in this screencast: http://railscasts.com/episodes/314-pretty-urls-with-friendlyid
For installation look here: https://github.com/norman/friendly_id
Both Andrew and Martin are right (the FriendlyID gem actually uses the to_param override method), but you're asking two questions :
can I use another attribute instead of the default id as the id in the route ?
can I use a non-resourceful route ?
In both cases, the answer is yes. You may override the to_param method AND use a non-REST route such as :
match '/:id' => 'users#show'

Resources