Question

class User
has_one :settings

class Settings
belongs_to :user

I want to do something like

@user_with_no_settings = User.where(:settings => nil)

But this returns an empty relation.

How do I find all users which don't have a settings related to them? (So I will find them and create them)

Était-ce utile?

La solution

Most importantly, your association is incorrect;

Change it to:

class User
has_one :setting

class Settings
belongs_to :user

The Class name is plural but the association has_one is always singular. So you can't use :settings for has_one as oppose to has_many which is always plural.

Use this:

User.where("id not in (select user_id from settings)")

The above query will give all the users which don't have a settings associated to them.

Autres conseils

Okay. In your situation you may need some TRY this code.

User.where('id NOT IN (?)', User.joins(:settings).pluck('settings.user_id'))

But, you need to follow Rails Convention.

Change settings to setting.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top