has-one

Rails: Create association if none is found to avoid nil errors

扶醉桌前 提交于 2019-11-29 08:37:19
问题 I have an application where my users can have a set of preferences. Both are stored as ActiveRecord-models as follows: class User < AR::Base has_one :preference_set end class PreferenceSet < AR::Base belongs_to :user end I can now access the preferences of a user: @u = User.first @u.preference_set => #<PreferenceSet...> @u.preference_set.play_sounds => true But this fails if a preference set is not already created, since @u.preference_set will be returning nil, and I'll be calling play_sounds

Difference between has_one and belongs_to in Rails? [duplicate]

ⅰ亾dé卋堺 提交于 2019-11-28 02:58:54
This question already has an answer here: What's the difference between belongs_to and has_one? 4 answers I am trying to understand has_one relationship in RoR. Let's say I have two models - Person and Cell : class Person < ActiveRecord::Base has_one :cell end class Cell < ActiveRecord::Base belongs_to :person end Can I just use has_one :person instead of belongs_to :person in Cell model? Isn't it the same? Sarah Mei No, they are not interchangable, and there are some real differences. belongs_to means that the foreign key is in the table for this class. So belongs_to can ONLY go in the class

Using build with a has_one association in rails

☆樱花仙子☆ 提交于 2019-11-26 16:53:44
In this example, I create a user with no profile , then later on create a profile for that user. I tried using build with a has_one association but that blew up. The only way I see this working is using has_many . The user is supposed to only have at most one profile . I have been trying this. I have: class User < ActiveRecord::Base has_one :profile end class Profile < ActiveRecord::Base belongs_to :user end But when I do: user.build_profile I get the error: ActiveRecord::StatementInvalid: Mysql::Error: Unknown column 'profiles.user_id' in 'where clause': SELECT * FROM `profiles` WHERE (