我想在我的汽车索引中显示用户名

时间:2017-03-16 09:25:10

标签: ruby-on-rails

这是我的汽车控制器.. 在索引方法中添加什么,以便我们在索引页面中获取用户的电子邮件

class CarsController < ApplicationController
  before_action :set_car, only: [:show, :edit, :update, :destroy]
  before_filter :authenticate_user! , except: [:index,:show]

  def index
    @cars = Car.all
  end

  def show
  end

  def new
    @car = current_user.cars.build
  end

  def edit
  end

  def create
    @car = current_user.cars.build(car_params)

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

这是我的索引。要在索引中添加什么来显示所有汽车中的用户电子邮件,所有用户都应该看到useremail

<%=@car.user.email%>
<div class="row" >
  <% @cars.each do |car| %>
    <div class="col-sm-8" >
      <div class="polaroid center-block" >
        <%=link_to (image_tag car.avatar.url(:medium)),car %>
        <div style="float:right">
        <p><%= link_to  edit_car_path(car) do %>
          <i class = "glyphicon glyphicon-edit "></i>
        <%end %></p>
        |
        <p><%= link_to  car, method: :delete, data: { confirm 'Are you       sure?' } do  %>
        <i class = "glyphicon glyphicon-trash"></i>
        <%end%></p></div>
      </div><br>
    </div>  
  <% end %>

我想显示在我的索引页面中发布汽车的用户的useremail。我应该在控制器和我的索引中添加什么来做...

1 个答案:

答案 0 :(得分:0)

如果您的汽车有关联belongs_to :user,请将其添加到您的控制器:@car = Car.includes(:user).all

在索引页面中,您可以添加<%= car.user.usermail %>