Search code examples
mysqlruby-on-railsruby-on-rails-4has-one

Rails 4 access table attributes from has_one association


i have two models User and account where

class User < ActiveRecord::Base
  has_one :account
end

 class Account < ActiveRecord::Base
      belongs_to :User
    end

in my users controller i am retrieving the users by

@user = User.list('', false,'company', 'asc')

where the "list" is a method described in my model to retrieve the records

in the users table i have two columns "id" and "company_name" and in the account table i have the columns as "user_id" and "country"

now i want the array @user to retrieve the company name and their country which can be found by user_id in accounts table

please tell me how can i do this thankx in advance


Solution

  • How about:

    # app/models/user.rb
    class User < ActiveRecord::Base
      has_one :account
    
      scope :with_account_info, -> { includes(:account) }
      default_scope{with_account_info}
    end
    

    The final two lines could be merged into one if you prefer that, i.e.:

    default_scope{ includes(:account) } 
    

    HTH