Answer the question
In order to leave comments, you need to log in
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}
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
Answer the question
In order to leave comments, you need to log in
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 %>
def index
@places = Place.where(user: current_user)
end
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question