Ruby on Rails
Monday, February 18, 2013
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? :)
Den måndagen den 18:e februari 2013 kl. 11:24:04 UTC+1 skrev Linus Pettersson:
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, CompanyA user belongs to a companyAn 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 :userbelongs_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_iderrors.add(:assigned_user, "användaren måste tillhöra samma företag")endendWhich 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.
Den måndagen den 18:e februari 2013 kl. 11:00:21 UTC+1 skrev Colin Law:On 18 February 2013 09:44, Linus Pettersson <linus.pe...@gmail.com> wrote:
> 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
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
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msg/rubyonrails-talk/-/BKKiLzR_jqcJ.
For more options, visit https://groups.google.com/groups/opt_out.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment