NooBskie NooBskie - 5 months ago 8
Ruby Question

Referencing belongs_to associations in view

I have activerecords attatched to my users in my

address
column via
user_id
I am trying to render a record belonging to a certain user in my view page but i keep on getting
NoMethodError


How do I call activerecords attached to a user id?

users.haml (view)



.row
.col-md-12
%table
%thead
%tr
%th Customer
%th Phone
%tbody
- @users.each do |user|
%tr
%td= link_to user.name, admin_customers_user_single_url(user.id)
%td= user.address.phone // this part


user.rb (model)



class User < ApplicationRecord
...
# associations
has_many :addresss
has_many :orders
...
end


address.rb (model)



class Address < ApplicationRecord
belongs_to :user
has_many :orders

validates :name,
:phone,
:address,
:city,
:country,
:post_code,
:province,
presence: true,
length: {minimum: 1}

# valid options for contact field
CONTACT_FIELD = ['al', 'ph', 'em', 'dn', 'tx']
validates_inclusion_of :contact, :in => CONTACT_FIELD

def get_contact
contact = {"al" => "All", "ph" => "Phone Only", "em" => "Email Only", "dn" => "Do Not Contact", "tx" => "Text Only"}
contact[self.contact]
end

def get_full_addr
buff = ""
buff << self.address
buff << ", " + self.address_2 if !(self.address_2.nil?)
buff << ", " + self.city
buff << ", " + self.province
buff << ", " + self.country
buff << ", " + self.post_code
end
end


customers_controller.rb (controller)



class CustomersController < ApplicationController
# users
def users
@users = User.all

respond_to do |format|
format.html do
@users = @users.paginate(:page => params[:page], :per_page => 50)
end
end
end

def get_user
@users = User.find(params[:id])
end
end

Answer

suggestion 1: plural for address is addresses

class User < ApplicationRecord
  ...
  # associations
  has_many :addresses  
  has_many :orders
  ...
end

Corrected view:

.row
  .col-md-12
    %table
      %thead
        %tr
          %th Customer
          %th Phone
          %tbody
            - @users.each do |user|
              %tr
                %td= link_to user.name, admin_customers_user_single_url(user.id)
                %td= user.addresses.map(&:phone) // all phones will be shown one by one if this man has many addresses.
Comments