Best way to add a second parameter to route - ruby-on-rails-3

I want my route to be something like cars(/:country/):car_id, what is the best way to do that? Only "cars" will list all the cars and "cars /: country" will list all the cars that are made in that country.
Now I have my route like this resources: cars,: path => "cars (/:country)" and I check in cars#index action if params[:country] is nil to determine what will be retrieved from the database .
My solution feels wrong and ugly and I guess the best solution and cleanest would be to make a country model, but do not really know how to organize it all up, tips?
country must have a slug and so do car_id too (using friendly_id for car_id). It feels like I should have a car table with name and slug thats all i have figured out.
Thanks!

First I'd say that your current solution is NOT ugly, nor wrong, at worst it's pedestrian. But without seeing all the involved models and associations, I can only give a general answer.
First, A country model, probably a good idea, but how do you relate it to the cars model?
You could do this:
class Country << ActiveRecord::Base
has_may :cars
end
class Car << ActiveRecord::Base
belongs_to :country
end
That would support semantics where by you could select a country, and get all cars belonging to a certain country, i.e.
#cars = Country.find('USA').cars
OR, you could do something like:
class Car << ActiveRecord::Base
has_one :country
end
class Country << ActiveRecord::Base
end
That would enable a different semantic:
#country = Car.find('Jeep').country
The point is to think of the query semantics you'd like to have in your app, and then define your associations to support the semantics that make sense for your app. I've posted very simple associations, you may end up with multiple and more complex associations, just depends on how you need to query the database and the associated models.
UPDATE
You posted:
I want my route to be something like cars(/:country/):car_id,
That doesn't make sense, if you know the specific car_id, you don't need any filtering or extra searching.
Sound like you want these URLs:
/cars # all cars
/cars/:country # all cars in country
/car/:id # a specific car
The first and third routes are probably there assuming you've defined the full set of RESTful routes for cars, i.e.
config/routes.rb
resources :cars
You just need to add to routes.rb:
GET '/cars/:country' => 'cars#index'
Then in app/controllers/cars_controller.rb:
def index
if params[:country]
#cars = Car.where("country_id = ?", params[:country])
else
#cars = Car.all
end
end
This assumes you have a relationship set up whereby each car record has a country_id attribute. That can come about in several ways, for example:
class Car < ActiveRecord::Base
belongs_to :country
end
That says my car table has a country_id attribute, and I can do something like:
#car = Car.find(1001)
"The car is in #{#car.country.name}"

Related

Rails: Is this a use case for Single Table Inheritance (STI)?

Consider this setup. Please understand that our setup is much more detailed but this is a simple example.
competition which has name. This is an annual competition.
competition_instances which has location, starts_at.
Each competition has sports which has name.
Example:
competition.name: "Super Bowl" has different competition_instances every year but sport remains the same.
Conversely, competition.name: "Olympics" has different competition_instances and different sports in each competition_instance.
Would it be best to create competition_sports and competition_instance_sports with competition_instance_sports as a subclass of competition_sports?
GOAL: Use competition_instance_sports records if they exist, otherwise use the competition_sports record. In our real world app, each competition/competition_instance can have 20-50 sport records. How can we best achieve?
Based on what I understand from the question I cannot see where STI will be helpful in this situation. However a join table will get you where you want.
I suggest creating a new table sports, this model will have all the specific details of each sport. The competition_instance.rb will have one/many sport.rb. competiton.rb will have many sports through competition_instance.rb.
competition.rb
Class Competition < ActiveRecord::Base
has_many :competition_instances
has_many :sports, through: :competition_instances
end
competition_instance.rb
Class CompetitionInstance < ActiveRecord::Base
belongs_to :competition
belongs_to :sport
end
sport.rb
Class Sport < ActiveRecord::Base
has_many :competition_instances
end
By using this design you will be able to achieve the following:
1- You will have your predefined sports in your database along with their specific properties.
2- Each competition will have .sports which will give all the sports in this competition for the olympics case.
3- You will be able to set specific properties for each competition instance (example event_start_time and event_end_time) in the competition instance table.
I'm just thinking of the case where there are standard sports which are always in the Olympics and some which are added on, such as those proposed by the host country.
I would use Polymorphic Associations, in a "reverse manner".
class Competition < ActiveRecord::Base
has_many :competition_instances
has_many :competition_sports, as: :event
end
class CompetitionInstance < ActiveRecord::Base
belongs_to :competition
has_many :competition_sports, as: :event
def events_array # neater by sacrificing ActiveRecord methods
competition.competition_sports + competition_sports
end
def events # messier, returns ActiveRecord relationship
CompetitionSport.where( " ( event_id = ? AND event_type = 'Competition' ) OR
( event_id = ? AND event_type = 'CompetitionInstance')", competition_id, id )
end
end
class Sport < ActiveRecord::Base
has_many :events, as: :competition_sport
end
class CompetitionSport < ActiveRecord::Base
belongs_to :sport
belongs_to :event, polymorphic: true
end
This allows:
competition.competition_sports # standard sports
competition_instance.competition_sports # only those specific for this instance
competition_instance.events # includes sports from both
Aiming at the original question of "Is this a use case for STI", it will be difficult to say if this is or not without seeing the full complexity of your environment. But here's are some things to consider:
Abridged from How (and When) to Use Single Table Inheritance in Rails - eugenius blog:
STI should be considered when dealing with model classes that share much of the same functionality and data fields, but you want more granular control over extending or adding to each class individually. Rather than duplicate code or forego the individual functionalities, STI permits you to use keep your data in a single table while writing specialized functionality.
You've simplified your example, but it sounds like competition and competition_instance are NOT essentially the same object, with minor behavioral differences. With what you've described, I would probably rename these objects to event and competition, or whatever makes better sense to you in terms of illustrating what these objects are actually representing. I think of 'The Olympics' as a generic event, and '100m Dash' as a competition taking place at The Olympics. Or "The SuperBowl" only hosted one competition in 2014, "SuperBowl XLIX".
You've also tagged this question with database-normalization, which STI won't help. If the attributes differ slightly between your shared objects you'll end up with null fields everywhere.
I refer you to the other answers here to see how you should probably set those objects up to behave as desired.
This is not a case for single table inheritance, because competition_instance is not a substitute for competition and 1 competition can have many competition_instances. So you have 3 tables:
competitions
sports
competition_instances
competition_instances has a foreign key to competitions because 1 competition can have many competition_instances but each competition_instance has exactly one competition.
Whether you attach sports to competitions or competition_instances depends on the specific constraints of your use case. I don't exactly know what you mean by "each competition/competition_instance can have 20-50 sport records". I would expect each competition_instance to have exactly one sport, so you might leave it at that, or you might attach a collection of sports to a competition as well, so that you can retrieve new competitions by sport before there is a competition_instance. I'd need more details on your use case to give you further advice.

Joining with named scopes in Ruby

I originally asked this question about acts_as_tree but it seems to be more general so I'm rephrasing it a bit here.
I have a model "category" using acts_as_tree. I often find myself needing to join it with other models for various queries, but I don't know how to use the provided scopes such as children, ancestors, siblings, descendants to create the conditions that I need.
Concrete example:
class Category < ActiveRecord::Base
acts_as_tree
has_many :photo
end
class Photo
belongs_to :category
end
cat = Category.first
How can I query for all the photos of children of cat or all the photos of its siblings?
Seems like I need something like:
Photo.joins(cat.children)
Photo.joins(cat.siblings)
which I know is not a valid code.
Since act_as_tree doesn't really use scopes but methods that return results, you can do it like:
class Photo
belongs_to :category
scope :from_category, -> (category) {
joins(:category).where(category: category)
}
end
cat = Category.first
Photo.from_category(cat.children)
Photo.from_category(cat.siblings)
And that should work.

Association between one model and an attribute of another

I'm trying to create an association for a beta meat-sale application between one model, Cuts, and the "animal_type" attribute of another model, Animal, such that I could list all the cuts associated with a particular animal_type (or associated with an animal that has that type as an attribute).
In other words, if animal_type is "cow", I should be able to call up a list of all the cuts (ribeye, tenderloin, etc) associated with cows. I'm new to Rails, and this is fairly above my head.
My idea was to create an animal_type column in Cuts and Animals, to associate each cut with a type of animal, so I could do something along the lines of
#cuts = Cut.where(:animal_type => Animal::animal_type[:Cow])
No idea if that works, though, and what else I need to do to make this association possible. Can anybody help point me towards a way of thinking this through? Or does anyone have any good resources I could look at to help me with this specific problem? I've been looking through Rails Guides, and they're helpful, but they don't really give me a way to answer this.
You could have a Cuts model and an Animal model. Cuts could have a string attribute called "name" which would store the cut type such as ribeye, tenderloin etc. Animal could have a string attribute called animal_type. You could then setup a has_many association between Animals and Cuts. Something like this:
class Animal < ActiveRecord::Base
attr_accessible :animal_type
has_many :cuts
end
class Cuts < ActiveRecord::Base
attr_accessible :name
belongs_to :animals
end
This should be a good start

BEGINNER: Correct seeds.rb in rails 3

I've just created two models and one "join table". Person, Adress (create_adresses_personss)
class Person < ActiveRecord::Base
has_and_belongs_to_many :streets
end
class Street < ActiveRecord::Base
has_and_belongs_to_many :persons
end
Now I want to add some data to these models in the db/seeds.rb file. The tutorial I follow just adds the objects:
person = Person.create :name => 'Dexter'
street.create[{:streetname => 'street1'},
{:streetname => 'street2'},
{:streetname => 'julianave'},
{:streetname => 'street3'}]
Question 1: Why is persons' data added differently than streets'? Is it just the tutorial that wants to show that there are many ways of adding data in the seeds.rb?
Question 2: The tutorial doesn't make the connections/joins in the seeds.rb. It does that in the rails console;
>>p1 = Person.find(1)
>>s1 = Street.find(1)
>>p1.streets << s1
Can't theese connections be made in the seeds.rb file?
Question 3: Would it be better to do this join with a "rich many_to_many-assocciation"?
Thanks for your time and patience with a beginner ;)
1) The first method is creating one object. The second method is creating multiple objects. However, for the second method you would need to do Street.create, not street.create.
2) Yes, you can do that in the seed file the same way.
3) The "Rich many-to-many" you're talking about is an association with a Join Model, I guess you're talking about. This is opposed to just a join table, which is what has_and_belongs_to_many does. To use a join model, you'll want to look up has_many :through. It's generally considered better to always use a proper join model, however I still use HABTM when I just need a quick, simple association. has_many :through allows for more options and more flexibility, but it is a little more complicated to setup (not that much, though). It's your decision.
One way that I like to create seed data for many-to-many associations is setting up one of the models, the adding a tap block that sets up the other models through the association.
Person.create!(:name => "Fubar").tap do |person|
3.times do |n|
person.streets.create!(:streetname => "street #{n}")
end
# OR
person.streets.create!([
{:streetname => "street 1"},
{:streetname => "street 2"},
... and so on
])
end
All tap is doing is executing the block with the object as it's only parameter. I find it convenient for seeds.
One other tip I would toss out there would be to have your model attribute names spaced on the words with underscores.
:street_name instead of :streetname
The difference is more profound when you start wanting to use some of the ActiveSupport helers that take model attributes and turn them into text strings for use in the UI.
e
:streetname.to_s.titleize # "Streetname"
:street_name.to_s.titleize # "Street Name"
And one last nitpick, you might want your join table to be addresses_people not addresses_persons since the rais inflector is going to pluralize person as people. The same would go for your controller on the Person model, PeopleController instead of PersonsController. Though maybe it will work with persons as well.
:person.to_s.pluralize # "people"
:people.to_s.singularize # "person"
:persons.to_s.singularize # "person"

Help with Rails find_by queries

Say if #news_writers is an array of records. I then want to use #news_writers to find all news items that are written by all the news writers contained in #news_writers.
So I want something like this (but this is syntactically incorrect):
#news = News.find_all_by_role_id(#news_writers.id)
Note that
class Role < ActiveRecord::Base
has_many :news
end
and
class News < ActiveRecord::Base
belongs_to :role
end
Like ennen, I'm unsure what relationships your models are supposed to have. But in general, you can find all models with a column value from a given set like this:
News.all(:conditions => {:role_id => #news_writers.map(&:id)})
This will create a SQL query with a where condition like:
WHERE role_id IN (1, 10, 13, ...)
where the integers are the ids of the #news_writers.
I'm not sure if I understand you - #news_writers is a collection of Role models? If that assumption is correct, your association appears to be backwards - if these represent authors of news items, shouldn't News belong_to Role (being the author)?
At any rate, I would assume the most direct approach would be to use an iterator over #news_writers, calling on the association for each news_writer (like news_writer.news) in turn and pushing it into a separate variable.
Edit: Daniel Lucraft's suggestion is a much more elegant solution than the above.