L
L
lavezzi12015-09-03 21:33:44
Ruby on Rails
lavezzi1, 2015-09-03 21:33:44

Why doesn't the same code work in different actions?

Hello.
In show.html.haml it works

%span #{@place.user.first_name} #{@place.user.last_name}

Index.html.haml no longer has
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

What should be written to extract users and display its data?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
C
CapeRatel, 2015-09-04
@CapeRatel

Everything is simple.
We start to discuss.
This before loads set_place only for show, edit, update, destroy actions.
In the index, you get a relation, an array of all places is simpler.
To get a user for each place, you need to iterate and call the user for each element

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

And you are trying to call a non-existent @place user in the index

_
_ _, 2015-09-03
@AMar4enko

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

UPD. You have an array in index in @places, show the index.html.haml template code

T
thepry, 2015-09-03
@thepry

Is it because the @place variable is not defined in index?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question