在视图中引用belongs_to关联

时间:2016-06-30 08:47:56

标签: ruby-on-rails ruby

我通过address在我的user_id列中为我的用户提供了有效的记录我试图在我的视图页面中呈现属于某个用户的记录,但我继续获取NoMethodError

如何调用附加到用户ID的activerecords?

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

4 个答案:

答案 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