haley
haley

Reputation: 1593

Rails: One to Many how to access data in the Many from the One

Hi I'm quite new to Rails so sorry if this is dumb. I've been searching for hours. Not even sure what to ask. Thanks so much for any help.

I'm trying to have a table with Codes and Descriptions. Then another Main table with the codes in it. Join these two tables so I can sort by the codes and pull the description. I can't seem to figure out the code to pull the description.

This is the Code and Description migration

create_table :sniffs do |t|
  t.string "sniff_desc", :limit => 5
  t.timestamps
end    

This is Main table migration

create_table :lenders do |t|
  t.integer "sniff_id"
  t.timestamps
end    

add_index("lenders", "sniff_id")

These are the models

class Lender < ActiveRecord::Base
  belongs_to :sniffs
  scope :ranked, order("lenders.sniff_id ASC")
end

class Sniff < ActiveRecord::Base
  has_many :lenders
end

The sniffs table is

id  sniff_desc
 1  Great
 2  OK
 3  Bad

lenders table is

id  sniff_id
 1  2
 2  2
 3  3

This is what I can't figure out? How for a specific lender instance do I get a sniff_desc. For example, I'm on lender.id(2) and I want to get it's sniff_desc "OK".

So if I'm rails console

    lender = Lender.find(2)
    lender.sniffs

I get

=> nil

I thought I'd get the second record in sniffs. If I type this

Sniff.find(lender.sniff_id).sniff_desc

I get the right answer

=> "OK" 

but that code seems to defeat the whole purpose of doing a one to many relationship.

Am I not understanding one-to-many correct? Or what do I do to fix this?

Thanks so much for any help. I think this question is too simple so I couldn't find anyone else asking it?!

Upvotes: 1

Views: 1436

Answers (1)

Mischa
Mischa

Reputation: 43298

You almost got it right. The only problem is that belongs_to uses singulars, not plurals.

You have to change:

belongs_to :sniffs

To:

belongs_to :sniff

With this you should be able to do:

lender = Lender.find(2)
lender.sniff.sniff_desc #=> "OK"

Upvotes: 1

Related Questions