我通过address
在我的user_id
列中为我的用户提供了有效的记录我试图在我的视图页面中呈现属于某个用户的记录,但我继续获取NoMethodError
如何调用附加到用户ID的activerecords?
.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
答案 0 :(得分:1)
用户有很多地址,因此您需要使用复数形式
= user.addresss.first.phone
不确定addresss
在语法上是否正确(我不是母语人士),但对我来说这看起来很奇怪。
答案 1 :(得分:1)
您的User
关联中存在拼写错误:
has_many :addresss
如果您的用户有一个地址,则必须使用has_one
关系:
class User < ApplicationRecord
...
has_one :address
...
end
此处有更多信息:Link
答案 2 :(得分:1)
建议1:地址复数是地址
class User < ApplicationRecord
...
# associations
has_many :addresses
has_many :orders
...
end
更正后的观点:
.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.
答案 3 :(得分:1)
应该是addresss
而不是2.2.2 :001 > a = "address"
=> "address"
2.2.2 :002 > a.pluralize
=> "addresses"
TIMESTAMPL
您可以使用rails pluralize方法检查任何单词的复数形式 - http://apidock.com/rails/ActiveSupport/Inflector/pluralize