lavezzi1
@lavezzi1

Почему один и тот же код но в разных экшенах не работает?

Здравствуйте.
В show.html.haml работает
%span #{@place.user.first_name} #{@place.user.last_name}


В index.html.haml уже нет

places_controller
class PlacesController < ApplicationController
  before_action :authenticate_user!
  before_action :set_place, only: [:show, :edit, :update, :destroy]

  def index
    @places = Place.where(user_id: current_user)
  end

  def show
  end

  def new
    @place = current_user.places.build
  end

  def edit
  end

  def create
    @place = current_user.places.build(place_params)

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

  def update
    respond_to do |format|
      if @place.update(place_params)
        format.html { redirect_to @place, notice: 'Place was successfully updated.' }
        format.json { render :show, status: :ok, location: @place }
      else
        format.html { render :edit }
        format.json { render json: @place.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    @place.destroy
    respond_to do |format|
      format.html { redirect_to places_url, notice: 'Place was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_place
      @place = Place.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def place_params
      params.require(:place).permit(:title, :description, :content)
    end
end


Что нужно написать, чтобы извлечь пользователи и отобразить его данные?
  • Вопрос задан
  • 232 просмотра
Пригласить эксперта
Ответы на вопрос 3
@CapeRatel
Все просто.
Начинаем рассуждать.
before_action :set_place, only: [:show, :edit, :update, :destroy]

Вот этот before загружает set_place только для экшенов show, edit, update, destroy

В индексе вы получаете relation, проще массив всех мест.
@places = Place.where(user_id: current_user)
Чтобы получить у каждого места юзера вам надо сделать перебор и у каждого элемента вызвать юзера

<% @places.each do |place| %>
       <% place.user.first_name %>
   <% end %>


А вы пытаетесь в индекс вызвать у несуществующего @place юзера
Ответ написан
AMar4enko
@AMar4enko
def index
  @places = Place.where(user: current_user)
end


UPD. У вас в index в @places массив, покажите код шаблона index.html.haml
Ответ написан
@thepry
Ruby on rails, 1С разработчик
Потому, что в index переменная @place не определена?
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы