ruby on rails - Creating a has_one association with an object which doesn't belong to anything -


i'll admit right off, i'm new rails, not programming in general or anything.

i followed michael hartl's tutorial , have decent understanding of how things work in safe , controlled space, i'm out in real world i'm having problems.

the little project i'm working on learn stuff simple rails app user can add song database , mark "favorite" track. while songs uploaded user, not owned user, because other user can pick uploaded song mark "favorite" well.

so makes sense me user model have

has_one :song validates :song_id, presence: true 

and song model have no association rules, because song doesn't "belong" user, belongs entire app user choose favorite.

however when try in rails console, , attempt user.song error thrown:

activerecord::statementinvalid: sqlite3::sqlexception: no such column: songs.user_id:   select  "songs".* "songs"  "songs"."user_id" = ?  order "songs"."id" asc limit 1 

i can see trying do, it's interpreting meaning songs model has user_id column join users table, want opposite. read documentation , found belongs_to association opposite, threw in user model instead this:

belongs_to :song validates :song_id, presence: true 

and works! but... doesn't make sense. user shouldn't belong anyone, should have favorite song. furthermore, doesn't make sense song object has_many users, because users, songs, aren't "owned" anyone, way tweet owned user, lets say.

i mean, if way (making users belong songs, , having songs have many users) i'm ok that, doesn't make sense me, , since i'm new rails figured there's better way of doing makes more sense in code of models.

thanks help!

the short answer rails way it.

the :belongs_to , :has_one predicates both 1-1 relations, , distinction indications on object primary key reference resides link 2 objects. natural choice of use falls out of whether relation might more 1-to-many or many-to-1.

:belongs_to means key reference local. used when using composition; if had shelves in cabinet, each shelf 'belongs to' cabinet, , cabinet 'has_many' shelf object. key on shelf, because object of there many.

:has_one means key reference on opposing object. used if might :has_many opposing object.

in case, imagine describing relationship song :has_many admirers, each of :belongs_to song (as admirer, via 'favorite' relation).

http://guides.rubyonrails.org/association_basics.html gives better overview many examples, including many-many relations.


Comments

Popular posts from this blog

user interface - How to replace the Python logo in a Tkinter-based Python GUI app? -

objective c - Greedy NSProgressIndicator Allocation -

how to set an OCR language in Google Drive -