activerecord - has_many or join - what's the 'rails way' to use my table? -


i have database keeps track of accidents. each accident can have multiple causes. each cause has friendly name in 3rd table. what's 'rails way' create association?

here's have:

create_table "accidents", force: true |t|   t.text     "notes"   t.datetime "created_at"   t.datetime "updated_at" end  create_table "causes", force: true |t|   t.integer  "accident_id"   t.integer  "cause_name_id"   t.datetime "created_at"   t.datetime "updated_at" end  create_table "cause_names", force: true |t|   t.string   "name"   t.datetime "created_at"   t.datetime "updated_at" end causename.create :name => "dui" causename.create :name => "speeding" 

accident:

class accident activerecord::base   has_many :causes end 

causes:

class cause < activerecord::base   belongs_to :accidents   has_one :cause_name end 

cause names:

class causename < activerecord::base   belongs_to :causes end 

it seems "orm"'d, i'd use this:

accident.causes.first.cause_name.name #speeding = causename.find(1) accident.causes.first.cause_name = #set , saved 

i've been trying variety of things, can't seem associations work way i'd expect. know i'm not using right.

i'm new rails , activerecord, , horrible databases... schema i'm working designed our dba doing reporting on table, knows nothing ruby or activerecord.

what's best approach in situation? using thing right?

i think have belongs_to , has_one methods placed incorrectly in cause - causename association.

quoting official guide:

if want set one-to-one relationship between 2 models, you'll need add belongs_to one, , has_one other. how know which?

the distinction in place foreign key (it goes on table class declaring belongs_to association), should give thought actual meaning of data well. has_one relationship says 1 of yours - is, points you.

so, in case, should this:

class causename < activerecord::base   has_one :cause # note have changed :causes singular end  class cause < activerecord::base   belongs_to :accident # <- singularized   belongs_to :cause_name end 

Comments

Popular posts from this blog

php - regexp cyrillic filename not matches -

c# - OpenXML hanging while writing elements -

sql - Select Query has unexpected multiple records (MS Access) -