0

I have a problem, I got a 'User' model and a 'Professional' model. Inside the Professional model, it is specified that it belongs to a user.

However, there is no written relation in the user model. There is nothing wrong it should be like that, a user can have a professional (thanks to the belongs_to), but not always.

Here is the problem: I can't do "User.find(49).professional" to test if the user n°49 is a professional (it should return a boolean).

However I can do "Professional.find(65).user", it returns true if the the professional n°65 is a user and false if he is not.

In some User view, I have this that doesn't work because of that:

- if @user.professional?
  div class="page-header"
    h1 Professional info
  ul style="list-style: none"
  // Id
  li
    strong
      = model_class.human_attribute_name(:id)
      ' :
    = @user.professional.id
  // Country
  li
    strong
      = model_class.human_attribute_name(:country)
      ' :
    = @user.professional.country

[...]

I got a wide "li" list. So, the if condition doesn't work, and the @user.professional.someprofessionalattributes doesn't work too.

What I first thought was that I should write in the User model "has_none_or_one", but it doesn't exist when I looked at the official docs.

Thanks for your help

Byscripts
  • 2,578
  • 2
  • 18
  • 25
sidney
  • 2,704
  • 3
  • 28
  • 44

2 Answers2

4

has_one is a has-one-or-none relationship. If a User doesn't have a corresponding Professional, then its Professional is nil.

Matchu
  • 83,922
  • 18
  • 153
  • 160
  • Thanks I didn't know, and it works like a charm very quickly ! Even after having read the doc, I don't think it was explained >_<" Thanks ! – sidney Jan 16 '13 at 17:55
  • @sidney: Glad to help. When an answer on StackOverflow answers your question, please be sure to click the check mark next to it to mark it as "accepted". This helps keep the site organized and makes sure that both the asker and the answerer get credit for being good citizens :) Thanks! – Matchu Jan 16 '13 at 22:55
1

Use to "has_one", for example:

Create this relationship

In the model User:

class User < ActiveRecord::Base
 has_one :professional, :dependent => :destroy
end

In the model Professional

class User < ActiveRecord::Base
 #add this parameter in yours attributes
 attr_accessible :user_id

 belongs_to :user
end

Add the index User to Professional model (create a migration).

rails g migration addIdUserToProfesional

In the migration created add this

class addIdUserToProfesional < ActiveRecord::Migration
  def change
    add_column :professionals, :user_id, :integer
    add_index :professionals, :user_id
  end
end

pdt: sorry my english still is not very well, Regards.