【问题标题】:Show User name instead of id in Rails partial view在 Rails 局部视图中显示用户名而不是 id
【发布时间】:2015-09-17 20:26:28
【问题描述】:

我知道必须有一个非常简单的解决方案,但我就是不知道怎么做。

在拍卖显示视图中,我正在显示所有出价的列表,其中包含相关出价人(=已出价的用户)。新出价时,user_id 成功保存在出价表中。

我想显示投标人姓名而不是他的 ID。 (@bidder = User.find(@bid.user_id))

bids_controller.rb:

class BidsController < ApplicationController
  # Create new bid
  def create
    # find Auction related to new Bid
    @auction = Auction.find(params[:auction_id])
    @bid = @auction.bids.create(bid_params)
    @bid.user_id = current_user.id
    # Find the bidder within User Table
    @bidder = User.find(@bid.user_id)
    @bid.save
    redirect_to auction_path(@auction), :notice => "Bid placed"
  end

出价部分视图:views\bids\ _bid.html.erb

<p>
  <strong>Bidder:</strong>
  <%= @bidder.name %>
</p>

<p>
  <strong>Bid-Amount:</strong>
  <%= bid.amount %>
</p>

<p>
  <%= link_to 'Destroy Bid', [bid.auction, bid],
              method: :delete,
              data: { confirm: 'Are you sure?' } %>
</p>

整个事情都显示在拍卖显示视图中:

视图\拍卖\show.html.erb

<h2>Bids</h2>
<%= render @auction.bids %>
<h2>Place a Bid:</h2>
<%= render 'bids/form' %>
<h2>Comments</h2>
<%= render @auction.comments %>
<h2>Add a comment:</h2>
<%= render 'comments/form' %>

错误:

拍卖中的 NoMethodError#show C:/Users/santa/Documents/rails/app/views/bids/_bid.html.erb 提出第 3 行的位置:

nil:NilClass 的未定义方法 `name' 提取的源代码(围绕行

3): 1 2 3 4 5 6

         <p>
<strong>Bidder:</strong>
<%= @bidder.name %>   </p>
 <p>

模板包含的痕迹:app/views/auctions/show.html.erb

名称存在于用户表中

【问题讨论】:

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


    【解决方案1】:

    尝试添加&lt;%= bid.user.name %&gt;,而不是&lt;%= @bidder.name %&gt;。如果user_id 正确保存在bid 表中,那么显然存在has_manybelongs_to 关联。

    只需将&lt;%= @bidder.name %&gt; 替换为&lt;%= bid.user.name %&gt;

    【讨论】:

    • 谢谢,就是这样! (不敢相信我花了 4 个小时尝试......)我会在 8 分钟内接受。
    • 好的。它发生在某个时候:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多