Jump to content

The ultimate community for Ruby on Rails developers.


Photo

cascading to an objects "name", not sure how when using two belongs_to to the same model...


  • Please log in to reply
3 replies to this topic

#1 jschrock1

jschrock1

    Dispatcher

  • Members
  • 45 posts
  • LocationIndianapolis

Posted 16 December 2013 - 07:42 PM

I have a model called "task" that contains two belongs_to for another model "user"

   belongs_to :user, foreign_key: "poster_id", dependent: :destroy
   belongs_to :user, foreign_key: "runner_id"
   belongs_to :job_sub_category
   belongs_to :job_category

In my views Im able to perform the following to retrieve the job_sub_category "name" field.

 

@task.job_sub_catebory.name

 

I also want to perform similar operation n the user model, such as this:

 

@task.runner_id.name

 

This of course errors "no method name on fixed num, but how would I be able to get the name of the user that exists in runner_id and for that matter the name of the user for poster_id.??

 

 



#2 Ohm

Ohm

    Guard

  • Members
  • 179 posts
  • LocationCopenhagen

Posted 16 December 2013 - 09:34 PM

You would want to define the belonging in a slightly different way, when you have multiple of the same class.

belongs_to :poster, class: 'User', dependent: :destroy
belongs_to :runner, class: 'User'
belongs_to :job_sub_category
belongs_to :job_category

I believe you can skip the foreign_key part, however I have not tested this.


Blog: http://ohm.sh | Twitter: madsohm


#3 jschrock1

jschrock1

    Dispatcher

  • Members
  • 45 posts
  • LocationIndianapolis

Posted 17 December 2013 - 07:15 PM

You would want to define the belonging in a slightly different way, when you have multiple of the same class.

belongs_to :poster, class: 'User', dependent: :destroy
belongs_to :runner, class: 'User'
belongs_to :job_sub_category
belongs_to :job_category

I believe you can skip the foreign_key part, however I have not tested this.

Thanks that worked...  although the syntax for me was a bit different..  Whooopa, onward!! 

 

 belongs_to :poster, :class_name => "User", :foreign_key => "poster_id", dependent: :destroy
 belongs_to :runner, :class_name => "User", :foreign_key => "runner_id"



#4 Ohm

Ohm

    Guard

  • Members
  • 179 posts
  • LocationCopenhagen

Posted 17 December 2013 - 10:34 PM

Yes, the syntax was different. I used the new Ruby 1.9 hash syntax.

{ one: 1, two: 2 }

which is a bit more concise than

{ :one => 1, :two => 2 }

Blog: http://ohm.sh | Twitter: madsohm





0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users