ruby-on-rails - Rails 4 - 如何从他们的 id 中获取用户名

标签 ruby-on-rails ruby-on-rails-4

我有一个如下所示的订单显示页面。我有这个工作,但自从我更换计算机以在这个应用程序上工作后,名称就没有显示。

如果我改变 <%= @order.user.name %><%= @order.user.id %> ,我得到了正确的 ID。否则,我不会显示应该发布 ID 名称的位置。

#view/orders/show.html.erb

<p>
  <strong>Code:</strong>
  <%= @order.code %>
</p>

<p>
  <strong>Client:</strong>
  <%= @order.client.name %>
</p>

<p>
  <strong>User:</strong>
  <%= @order.user.name %>
</p>

<p>
  <strong>Notes:</strong>
  <%= @order.memo %>
</p>

<p>
  <strong>Status:</strong>
  <%= @order.status ? "Confirmed" : "In Progress"  %>
</p>



<%= link_to 'Edit', edit_order_path(@order) %> |
<%= link_to 'Back', orders_path %>

#models/order.rb 片段

class Order < ActiveRecord::Base
    belongs_to :user
end

#model/user.rb

class User < ActiveRecord::Base
  has_many :orders, dependent: :destroy
  has_many :addresses, dependent: :destroy
  has_many :telephones, dependent: :destroy

  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

    enum role: [:user, :manager, :admin]
  after_initialize :set_default_role, :if => :new_record?

  def set_default_role
    self.role ||= :user
  end
end

#controllers/order_controller.rb 片段

  def create
    @order = Order.new(order_params)
    @order.user_id = current_user.id
    @order.status = TRUE

    respond_to do |format|
      if @order.save
        format.html { redirect_to @order, notice: 'Order was successfully created.' }
        format.json { render :show, status: :created, location: @order }
      else
        format.html { render :new }
        format.json { render json: @order.errors, status: :unprocessable_entity }
      end
    end
  end

最佳答案

我想我刚刚回答了你的另一个问题,但我建议使用 .delegate像这样的方法:

#app/models/order.rb
Class Order < ActiveRecord::Base
   belongs_to :user
   delegate :name, to: :user, prefix: true #-> @order.user_name
end

如果需要,您可以委托(delegate)多个变量。 这修复了 Law of Dementer ,如所述here

关于ruby-on-rails - Rails 4 - 如何从他们的 id 中获取用户名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24130311/

相关文章:

ruby-on-rails - 参数错误 : Factory not registered

ruby-on-rails-4 - Gmaps 未在 rails 4 + gmaps4rails 2.0.3 中定义

ruby-on-rails - ActiveRecord 传递关联删除

ruby-on-rails - 使用 rspec-rails 在所有 View 规范上 stub 模板方法的正确方法是什么?

sql - 多个 has_many 关系 Rails SQL 查询

ruby-on-rails - 充当Voable获取Upvotes错误

ruby - Mongoid 是否可以覆盖 updated_at 时间戳

ruby-on-rails - 给定一个字符串,判断它是否来自 .html_safe 调用?

ruby-on-rails - Capistrano 部署后 Rails Assets 未编译

ruby-on-rails - 使用 Postgresql 在 OS X Lion 上安装 Sphinx