Use variable other than :id in rails 3 routes - ruby-on-rails

I'm trying to get my rails 3 app to use a route that looks something like:
exampleapp.com/patients/123456
rather than
exampleapp.com/patients/1
where "123456" would be associated with the patient's medical record number (:mrn), which is already in the :patients table and is a unique integer. I want to use the :mrn in place of the usual :id. How would I go about this?
Sorry if this has already been asked - I couldn't find the terminology as to what I'm trying to do is called. Thanks!

You could do this,
class Patient < ActiveRecord::Base
self.primary_key = "mrn"
end
However, this will change a bunch of other things. The to_params will use mrn. The controller will still use params["id"], but the value will be the mrn field. The Patient.find method will work on the mrn field, but not the id field. (You can user Patient.find_by_mrn and Patient.find_by_id which will work on their specified fields.) Also, all foreign keys will be to the mrn value.
You can edit the mrn field, and you will still have an id field (unless you turn it off), however, editing could be a pain because all the foreign keys will have to be corrected.
Alternatively, if you just want to change the URL, then in your config/routes.rb file instead of
resources :patient
use
match "/patients/:mrn" => "patients#show"
match "/patients/:mrn" => "patients#update", :via => :put

You could just add this to your Patients model
def class Patient < ActiveRecord::Base
self.primary_key = "mrn"
end

You can get per-resource identifier customization by redefining the member_scope and nested_scope methods on the Resource instance.
resources :patients do
#scope[:scope_level_resource].tap do |u|
def u.member_scope
"#{path}/:mrn"
end
def u.nested_scope
"#{path}/:#{singular}_mrn"
end
end
end

Related

What routes are necessary when the Model and Controller names do not match?

I have a Model called Category and another called Articles. Categories are "sections" that have many Articles, for instance News and Events. Both Categories use the kind of Articles, except they're shown under a different section of my website.
Right now I'm creating the News controller (NewsController), and I'd like to visit /news/new to add News. Likewise, the same would apply to EventsController and /events/new.
What do I have to use on my routes to do this?
My first attempt was to use:
resources :categories do
resources :articles, path: '/news'
end
But this forces me to use /categories/1/news/new, which is kinda ugly.
If News will always be category_id 1 and Events will always be 2, how would I specify this on my routes, so I can easily access them with the URLs I mentioned?
Explained Differently
I have an Articles model. I'd like to have a controller called NewsController to handle Articles, so that /news/new (and the rest of the paths) would work with Article. I'd also like to have a controller called EventsController that would also handle Articles, so that /events would also work with Article. The difference between them is that they have different category_id.
Is this possible to do via routes?
Update
Made some progress.
resources :categories do
resources :articles
end
get 'news/new' => 'articles#new', defaults: {category_id: 1}
get 'events/new' => 'articles#new', defaults: {category_id: 2}
This fixes what I wanted to do with /news/new and /events/new, but I'd be missing the rest of the routes (edit, show, update, etc). Also, this makes me use the Articles controller, which currently does not exist and would also make the News controller obsolete/useless.
My logic may be wrong, it's kinda evident with what I just made, but perhaps with this update I can better illustrate what I'm trying to do.
Update 2
I'm currently testing the following:
resources :articles, path: '/news', controller: 'news'
resources :articles, path: '/events', controller: 'events'
So far it makes sense, it makes the routes I wanted, it uses both controllers with their own configurations, and it hasn't spat any errors when I visit both /news and /events (yet).
It's also possible to do:
resources :articles, path: '/news', defaults: {category_id: 1}
resources :articles, path: '/events', defaults: {category_id: 2}
But this would depend on an Article controller, which could handle both types of Categories. Either solution works (theoretically), though I'd incline more on the first since the individual controllers would allow more specific configuration to both cases. The second, though, is more adequate when there're not that many difference between the Articles being created. The defaults property isn't explicitly necessary either, I just put it there for convenience.
Your question is asking something that I question as not making sense and maybe your design is flawed.
Why would you have news resources related to category resources if they are not related?
Is categories just a name space?
If news records really are always going to be related to the same first category as your question implies then you can not use ID's as you have no control over what the id will be for the first category and the first category could have an ID of anything in which case you could just use the top level news resources and do a find first category in your model in a before create then you don't have to worry about an ugly url.
If news records really are related to categories then the you must supply the relevant category id and nest your routes but you could pretty up the url using the following from
https://gist.github.com/jcasimir/1209730
Which states the following
Friendly URLs
By default, Rails applications build URLs based on the primary key --
the id column from the database. Imagine we have a Person model and
associated controller. We have a person record for Bob Martin that has
id number 6. The URL for his show page would be:
/people/6
But, for aesthetic or SEO purposes, we want Bob's name in the URL. The
last segment, the 6 here, is called the "slug". Let's look at a few
ways to implement better slugs. Simple Approach
The simplest approach is to override the to_param method in the Person
model. Whenever we call a route helper like this:
person_path(#person)
Rails will call to_param to convert the object to a slug for the URL.
If your model does not define this method then it will use the
implementation in ActiveRecord::Base which just returns the id.
For this method to succeed, it's critical that all links use the
ActiveRecord object rather than calling id. Don't ever do this:
person_path(#person.id) # Bad!
Instead, always pass the object:
person_path(#person)
Slug Generation
Instead, in the model, we can override to_param to include a
parameterized version of the person's name:
class Person < ActiveRecord::Base def to_param
[id, name.parameterize].join("-") end end
For our user Bob Martin with id number 6, this will generate a slug
6-bob_martin. The full URL would be:
/people/6-bob-martin
The parameterize method from ActiveSupport will deal with converting
any characters that aren't valid for a URL. Object Lookup
What do we need to change about our finders? Nothing! When we call
Person.find(x), the parameter x is converted to an integer to perform
the SQL lookup. Check out how to_i deals with strings which have a mix
of letters and numbers:
"1".to_i
=> 1
"1-with-words".to_i
=> 1
"1-2345".to_i
=> 1
"6-bob-martin".to_i
=> 6
The to_i method will stop interpreting the string as soon as it hits a
non-digit. Since our implementation of to_param always has the id at
the front followed by a hyphen, it will always do lookups based on
just the id and discard the rest of the slug. Benefits / Limitations
We've added content to the slug which will improve SEO and make our
URLs more readable.
One limitation is that the users cannot manipulate the URL in any
meaningful way. Knowing the url 6-bob-martin doesn't allow you to
guess the url 7-russ-olsen, you still need to know the ID.
And the numeric ID is still in the URL. If this is something you want
to obfuscate, then the simple scheme doesn't help. Using a Non-ID
Field
Sometimes you want to get away from the ID all together and use
another attribute in the database for lookup. Imagine we have a Tag
object that has a name column. The name would be something like ruby
or rails. Link Generation
Creating links can again override to_param:
class Tag < ActiveRecord::Base validates_uniqueness_of :name
def to_param
name end end
Now when we call tag_path(#tag) we'd get a URL like /tags/ruby. Object
Lookup
The lookup is harder, though. When a request comes in to /tags/ruby
the ruby will be stored in params[:id]. A typical controller will call
Tag.find(params[:id]), essentially Tag.find("ruby"), and it will fail.
Option 1: Query Name from Controller
Instead, we can modify the controller to
Tag.find_by_name(params[:id]). It will work, but it's bad
object-oriented design. We're breaking the encapsulation of the Tag
class.
The DRY Principle says that a piece of knowledge should have a single
representation in a system. In this implementation of tags, the idea
of "A tag can be found by its name" has now been represented in the
to_param of the model and the controller lookup. That's a maintenance
headache. Option 2: Custom Finder
In our model we could define a custom finder:
class Tag < ActiveRecord::Base validates_uniqueness_of :name
def to_param
name end
def self.find_by_param(input)
find_by_name(input) end end
Then in the controller call Tag.find_by_param(params[:id]). This layer
of abstraction means that only the model knows exactly how a Tag is
converted to and from a parameter. The encapsulation is restored.
But we have to remember to use Tag.find_by_param instead of Tag.find
everywhere. Especially if you're retrofitting the friendly ID onto an
existing system, this can be a significant effort. Option 3:
Overriding Find
Instead of implementing the custom finder, we could override the find
method:
class Tag < ActiveRecord::Base #... def self.find(input)
find_by_name(input) end end
It will work when you pass in a name slug, but will break when a
numeric ID is passed in. How could we handle both?
The first temptation is to do some type switching:
class Tag < ActiveRecord::Base #... def self.find(input)
if input.is_a?(Integer)
super
else
find_by_name(input)
end end end
That'll work, but checking type is very against the Ruby ethos.
Writing is_a? should always make you ask "Is there a better way?"
Yes, based on these facts:
Databases give the id of 1 to the first record
Ruby converts strings starting with a letter to 0
class Tag < ActiveRecord::Base #... def self.find(input)
if input.to_i != 0
super
else
find_by_name(input)
end end end
Or, condensed down with a ternary:
class Tag < ActiveRecord::Base #... def self.find(input)
input.to_i == 0 ? find_by_name(input) : super end end
Our goal is achieved, but we've introduced a possible bug: if a name
starts with a digit it will look like an ID. If it's acceptable to our
business domain, we can add a validation that names cannot start with
a digit:
class Tag < ActiveRecord::Base #... validates_format_of :name,
:without => /^\d/ def self.find(input)
input.to_i == 0 ? find_by_name(input) : super end end
Now everything should work great! Using the FriendlyID Gem
Does implementing two additional methods seem like a pain? Or, more
seriously, are you going to implement this kind of functionality in
multiple models of your application? Then it might be worth checking
out the FriendlyID gem: https://github.com/norman/friendly_id Setup
The gem is just about to hit a 4.0 version. As of this writing, you
want to use the beta. In your Gemfile:
gem "friendly_id", "~> 4.0.0.beta8"
Then run bundle from the command line. Simple Usage
The minimum configuration in your model is:
class Tag < ActiveRecord::Base extend FriendlyId friendly_id :name
end
This will allow you to use the name column or the id for lookups using
find, just like we did before. Dedicated Slug
But the library does a great job of maintaining a dedicated slug
column for you. If we were dealing with articles, for instance, we
don't want to generate the slug over and over. More importantly, we'll
want to store the slug in the database to be queried directly.
The library defaults to a String column named slug. If you have that
column, you can use the :slugged option to automatically generate and
store the slug:
class Tag < ActiveRecord::Base extend FriendlyId friendly_id
:name, :use => :slugged end
Usage
You can see it in action here:
t = Tag.create(:name => "Ruby on Rails")
=> #
Tag.find 16
=> #
Tag.find "ruby-on-rails"
=> #
t.to_param
=> "ruby-on-rails"
We can use .find with an ID or the slug transparently. When the object
is converted to a parameter for links, we'll get the slug with no ID
number. We get good encapsulation, easy usage, improved SEO and easy
to read URLs.
If you are sure there will be only 2 categories, why not simply add a boolean to the articles?
Like: article.event = true if events category, false if news
Then you can add a scopes to Article class for both categories
class Article
scope :events, -> { where(event: true) }
scope :news, -> { where(event: false) }
end
Create controllers, for example:
class EventsController < ApplicationController
def index
#articles = Article.events
end
def create
#article.new(params)
#article.event = true
#article.save
end
...
end
and routes: resources :events
You should try to use dynamic segments: http://guides.rubyonrails.org/routing.html#route-globbing-and-wildcard-segments
Add some slug attribute to Category, it should be unique and add index to it.
# routes
resources :articles, except: [:index, :new]
get '*category_slug/new', to: 'articles#new'
get '*category_slug', to: 'articles#index'
# controller
class ArticlesController < ApplicationController
def index
#category = Category.find_by slug: params[:category_slug]
#articles = #category.articles
end
def new
#category = Category.find_by slug: params[:category_slug]
#article = #category.articles.build
end
...
end
Remember to put a category in a hidden field in the form_for #article

rails active record has_many foreign key after custom function

Consider following models
class User < AR
has_many :resources
end
class Resource < AR
belongs_to :user
end
I have a requirement where the foreign key is saved after applying some function on it. So the value of user_id in resources table does not match id in users table but it can be calculate again from id.
How can I define the association? Let's say that function is dummy_func().
Since belongs_to returns class instance instead of association, you can define methods in Resource class
class Resource < ApplicationRecord
def user
User.find(user_id)
end
def user=(user)
user_id = user.id
end
end
Similar for has_many result in user can be achieved by creating common relation in resources method
class User < ApplicationRecord
def resources
Resource.where(user_id: id)
end
end
So, if you use this code, you can replace any ids in Resource model, and behavior will exactly same as in belongs_to (Maybe there is some difference in depths). And you can achieve very similar behavior in User model, by writing methods by yourself.
Perhaps you can you can use a callback in order to modify the current user_id somehow before saving it: callbacks.
I'd suggest something like :before_save or something of that nature where you define how you want the user_id to be modified in the resources table and then have a way of decrypting it as well.
Maybe you can use an encryption gem to encrypt and decrypt your attribute like attr-encrypted.
Hope this helps a bit!
In the User model, you can override the setter. If you want to encrypt and decrypt the user ID (using attr_encrypted)...
You could try something like this:
attr_encrypted :id, key: ENCRYPTION_KEYS[:value]
def id=(value)
send("encrypted_value=", encrypt(:id, value))
instance_variable_set(:#id, value)
end
Then you can make a method that decrypts the ID
def decrypted_id
decrypt(:id, encrypted_value)
end
Now, when the User is created, the database will set the ID as usual. But it will also create an encrypted_value which stores the id as an encrypted ID. You can use this encrypted value around your app to keep the database ID secret from the interface.
Here is an example in console...

Scoping a class method to current_user

I'm working on implementing a tagging system and I'm having problem querying for tagged objects with a scope.
For example, I would like to find all the user's items with a certain tag. With a class method I can currently find all the objects:
def self.tagged_with(name)
Tag.find_by_name(name).items
end
However, this has a problem. If I were to do something like: current_user.items.tagged_with(name) won't this existing method return ALL the items and not just items owned by the current_user? I suppose this is a simply querying issue but I can't figure out how to change a class method into something called on a collection. I have tried going the opposite way, to get a the collection through the tags, something like... tag.items.where(:user_id => current_user.id) but in this case, it's a many-to-many relationship and I haven't been able to get on thumb on this either.
What's the proper way to restrict a query like this?
Create an association on your User class that points to your Tag class.
class User < ActiveRecord::Base
has_many :tags
end
Then you can do:
current_user.tags.where(...)
If you don't already have an association in place, you'll need to create a migration to have the tags table reference your users table with a foreign key.
I think this will help you:
class Account < ActiveRecord::Base
has_many :people do
def find_or_create_by_name(name)
first_name, last_name = name.split(" ", 2)
find_or_create_by_first_name_and_last_name(first_name, last_name)
end
end
end
person = Account.first.people.find_or_create_by_name("David Heinemeier Hansson")
person.first_name # => "David"
person.last_name # => "Heinemeier Hansson"
So, basically you can define your method tagged_with directly into the association!
This example is took from the documentations ActiveRecord::Associations

Rails 3: Hash accessor in the model?

I'm struggling to stretch my understanding of some basic Rails concepts beyond the tutorial examples I've done. I can't find any Q&A/docs/walkthroughs doing what I'm trying to do, so there's a good chance I'm going about this the wrong way.
I have a Team object with many Tags. The Team table has a few normalized fields, but most of the characteristics of the team are stored as Tags, i.e the Team 'Virginia Cavaliers' has Tags
{[tag_name => 'Conference', tag_value => 'ACC'],
[tag_name => 'Division', tag_value =>'I']}
etc. The db design was meant to accommodate many types of teams in the same table, with the tag table facilitating search for teams by arbitrary criteria.
So far so good. What I can't figure out is how to best access the team attributes given the team.
class Team < ActiveRecord::Base
belongs_to :sport
has_many :team_subscriptions
has_many :users, :through => :team_subscriptions
has_many :tags
def tagvalue
#Set up a hash to retrieve tag value by name?
#tagvalue = {}
tags.each do |t|
#tagvalue[t.tag_name] = t.tag_value
end
Rails.logger.info(#tagvalues.keys)
end
end
The hash is there but I can't access it in a view the way I'd like.
<%= #team.tagvalue["Conference"] %>
Is this sensible? possible? Thanks for your responses.
* Edited based on feedback (This site is awesome)*
The second suggestion is slick syntacticly, but has two hang ups I can see. I have to catch nulls as not all teams have all tags and sometimes they show up in the same list:
My clumsy implementation:
has_many :tags do
def [](key)
set = where(:tag_name => key)
if set.length > 0
set.first[:tag_value]
end
nil
end
end
The clean code thanks to edgerunner:
has_many :tags do
def [](key)
where(:tag_name => key).first.try(:tag_value)
end
end
And if I'm not wrong this method makes extra database calls every time I access a tag. The first method needs just one when the object is instantiated. Did I get both of those right?
There may be a different way to do the same. You can define an anonymous association extension and define the array accessor method for that to retrieve the tags with keys.
class Team < ActiveRecord::Base
...
has_many :tags do
def [](key)
where(:tag_name => key).first.try(:tag_value)
end
end
...
end
This will let you fetch only the required tags from the database instead of getting them all at once just to use one of them. It lets you do this:
<%= #team.tags["Conference"] %>

Enforcing a Uniqueness Constraint in a Nested Form

I'm trying not to fight the defaults here and use Rails built-in support for nested attributes (from http://ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes). I'm labeling Things with Tags, and all works swell, and for each Thing I have a form with a nested field that creates a new Tag by a name. Trouble is, I need to make sure that each Tag has a unique name. Instead of creating a new Tag, if a user enters the name of one that already exists, I need to create the associate with that pre-existing Tag. How do I do this?
There's probably a better way to do this but this is about the best I can come up with for now.
In a has_many(:through) association accepts_nested_arguments_for uses an assignment to the virtual attribute #{association}_attributes to work its magic. It expects an array of hashes, where each hash contains attribute keys and their values. Any hashes with an id will be updated (or deleted if there is a :_delete key with the value of true). Any hashes missing an id will be used to create new items of that association. So the key is to intercept the call to tags_associations= and check any of the hashes that are missing ids for an existing tag with the same name value, and replace it with an entry that tags_attributes will use to make the association to the existing tag. N.B. for has_one and belongs_to relationships tag_attributes will expect a single hash. The code will be similar, but much simpler.
class Thing < ActiveRecord::Base
has_many :tags, :through => :taggings
has_many :taggings
accepts_nested_attributes_for :tags
def tags_attributes_with_recycling=(attributes)
existing_attributes = attributes.reject{|attribute| attribute[:id].nil?}
new_attributes = attributes - existing_attributes
new_and_recycled_attributes = new_attributes.map { |attribute|
tag_id = Tag.find_by_name(attribute[:name]).id
tag_id ? {:id => tag_id) : attribute
}
tags_attributes_without_recycling= (existing_attributes + new_and_recycled_attributes)
end
alias_method_chain :tags_attributes=, :recycling
end
It's untested, so no guarantees. But it should at least put you on track for a solution.
In your Thing class, define a tags_attributes= method to override the default and use Tag.find_or_create
def tags_attributes=(attributes)
attributes.each do |attr|
Tag.find_or_create_by_name(attr[:name])
end
end
Not sure what the attributes hash will look like but you get the idea.

Resources