Reputation: 3841
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?
.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
class User < ApplicationRecord
...
# associations
has_many :addresss
has_many :orders
...
end
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
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
Upvotes: 0
Views: 108
Reputation: 3323
It should be addresses
instead of addresss
2.2.2 :001 > a = "address"
=> "address"
2.2.2 :002 > a.pluralize
=> "addresses"
You can use rails pluralize method to check the plural of any word - http://apidock.com/rails/ActiveSupport/Inflector/pluralize
Upvotes: 1
Reputation: 1285
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.
Upvotes: 1
Reputation: 2464
User has many addresses, so you need to use plural form
= user.addresss.first.phone
Not sure addresss
is grammatically right (I'm not a native speaker), but it looks weird for me.
Upvotes: 1