如何将用户模型中的用户名显示为引用控制器的索引视图?

时间:2015-08-01 19:13:58

标签: ruby-on-rails controller associations erb

当我创建引号时,它会询问引用正文,作者和用户ID,用户和引号是否已关联,但我想显示用户的用户名,其中包含创建报价时用户的用户ID。因此,如果用户具有用户名“shanks”并且他的ID为4并且当用户创建引号并且在user_id的文本字段中他输入4 ...我想在报价控制器的索引视图中显示用户的用户名有那个id。

def index
    @quote = Quote.new
    @quotes = Quote.order(created_at: :desc).all
    @user = User.new
end

视图:

<!-- form to add a Quote -->
<div class="create-quote">
<%= form_for @quote do |f| %>
<%= f.label :quotetext %><br>
<%= f.text_field :quotetext %><br>

<%= f.label :author %><br>
<%= f.text_field :author %><br>

<%= f.label :user_id %><br>
<%= f.text_field :user_id %><br>
<%= f.submit "Add quote" %>
<% end %>
</div>
<!-- All quotes here -->
<% @quotes.each do |quote| %>
<blockquote>
    <p>
        <%= quote.quotetext %>
    </p>
    <footer>
        <cite> 
            <%= quote.author %><br>
        </cite>
        <p>Posted by: <%= @user.username %> </p> <!-- this -->
    <%= link_to "Delete quote", quote_path(quote), method: :delete, data: { confirm: "Are you sure you want to delete this beautiful quote?"}     %>
    </footer>
</blockquote>
<%= quote.like %></br>
<% end %>

用户模型:

class User < ActiveRecord::Base
has_many :quotes
validates :username ,presence: true
validates :password ,presence: true
end

引用模型:

class Quote < ActiveRecord::Base
belongs_to :user
validates :quotetext, presence: true,
    length: { minimum: 5}
validates :author, presence: true
end

1 个答案:

答案 0 :(得分:1)

您的报价与用户有关,因此当您执行此操作时,它会为您提供用户对象

    quote.user

现在当您执行quote.user.username时,它将为用户提供与报价相关的用户名。

使用此

    <p>Posted by: <%= quote.user.try(:username) %> </p>