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
@items = Item.joins(:suplier).where(:suplier => { :name => "Suplier name" })
Supplier.find_by_colname(params[:name])
Where colname
is the name of Supplier table column
in which we want to check our parameter value. In rails we can just append column name with the find_by_
as shown above and rails will show you it's magic ;) . Here is the reference in Doc
精彩评论