Search code examples
ruby-on-railsruby-on-rails-3model-associations

Issue in alias model name in rails


I have two models User and Dtype. In users table I have two column named dtype_id and dtype_second which contains ID's of Dtype. Now I need to get both the columns values through association.

Using @user.dtype.name will give me the value of first column (dtype_id).

Now, I also need the value of second column i.e dtype_second.

For this I'm trying this:

In User Model:
belongs_to :dtype

In Dtype Model:
has_many :users
has_many :dtype_seconds, :foreign_key => 'dtype_second', :class_name => "User"

On view:
<%= @user.dtype_seconds.name %>

The issue is that I'm not getting any value or error.


Solution

  • Your are adding a has many to dtype, but you're trying to call the method on a user. So you have to define the dtype_second association on the user:

    class User < ActiveRecord::Base
      belongs_to :dtype
      belongs_to :dtype_alternative, :foreign_key => 'dtype_second', :class_name => "Dtype"
    
      ...
    end
    
    <%= @user.dtype_alternative.name %>