Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 - Find by name instead of id

I'm trying to learn RoR, building my first app, a basic inventory application. I've tried searching around but could not find the correct syntax, so I thought I would ask.

Here's my set up:

Model

class Item < ActiveRecord::Base
belongs_to :supplier

class Supplier < ActiveRecord::Base
has_many :items

Items Controller

@items = Item.find_all_by_supplier_id '1'

This will return the data that I want, but I was hoping to input the supplier name into the controller so that if the ID does not match up it will still work properly.

Hope that's enough info, thanks!

like image 253
rmp Avatar asked Apr 06 '11 20:04

rmp


1 Answers

You could invert your method bit and try:

@items = Supplier.find_by_name('THE NAME').items

Rails creates dynamic find_by_* and find_all_by_* methods for searching. Instead of retrieving items by the supplier_id, I recommend you let rails do this for you with the associations you have set up as in the code snippet above. Internally, this still uses the supplier_id, but rails is handling the process instead of you.

The inverse of this is also possible, so if you have an item and want the supplier, you can do:

Item.find(1).supplier
like image 196
Gazler Avatar answered Oct 05 '22 00:10

Gazler