belongs_to condition that checks the current user?

Hi

I have a model, let’s call it entry, that belongs to a user. The user and the entry also belongs to a company.

Can I add a condition on the belongs_to relations to check this?

Something like:

belongs_to :assigned_user, class_name: “User” , conditions: { company_id: company_id }

This doesn’t work because company is set on the Entry in the create action, like this:

def create

@entry.company = current_user.company

And current_user is the Devise helper and not available in the model.

So, can I achieve this somehow?

Why have you got Entry belongs_to company? If it also belongs_to user and user belongs_to company then you can just say @entry.user.company. If you want to be able to say @entry.company then you can use delegate.

Colin

That is true. I’ll probably change this.

This doesn’t solve my problem though. I realize that I phrased myself a bit odd in my first post I will clarify below.

I have three models, User, Entry, Company

A user belongs to a company

An Entry belongs to the User who creates it.

An entry can also be assigned to another user (think of it like a task). So, I have these relationships in Entry:

belongs_to :user

belongs_to :assigned_user, class_name: “User”

The :assigned_user relationship should only be to a user who is related to the same company as :user. I validate it like this:

def assigned_user_must_be_in_company

if assigned_user.present? && assigned_user.company_id != user.company_id

errors.add(:assigned_user, “användaren måste tillhöra samma företag”)

end

end

Which works OK.

But it would be nice to also have a constraint for this on the relation itself to get the correct users automatically etc.

Also, about the relationship with company. If Entry is not related to Company, how do you deal with:

  1. A user is deleted (the company may still want to see her Entries?)

  2. Isn’t it inefficient to get all Entries from a company?

company.users.each do …

Instead of just:

company.entries

Or am I wrong? :slight_smile:

Also, about the relationship with company. If Entry is not related to Company, how do you deal with:

1. A user is deleted (the company may still want to see her Entries?)

Don't actually delete the user while she still has entries. Just mark her as inactive or whatever is appropriate. If the entries are still of interest then it may be of interest who created the entry even if she has gone.

2. Isn't it inefficient to get all Entries from a company? company.users.each do ....

Instead of just: company.entries

Company   has_many :users   has_many :entries, :through => :users

Then you can say @company.entries

Colin