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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With