Reputation: 2305
Showing all user's photos works , but showing particular photos of one user don't (shows missing image instead of those defind by id). Route for getting particular image is /users/:user_id/photos/:id
. This is my Photos controller:
class PhotosController < ApplicationController
before_action :find_user, only: [:index, :new, :create, :update]
before_action :find_photo, only: [:show, :destroy]
def index
@photos = @user.photos
end
def new
@photo = @user.photos.build
end
def show
end
def create
@photo = Photo.new(photo_params)
if @photo.save
if params[:images]
params[:images].each { |image|
@user.photos.create(image: image)
}
end
redirect_to :action => :index
else
render 'new'
end
end
def update
@photo = @user.photos.find(params[:id])
if @photo.update
redirect_to user_photos
else
render 'edit'
end
end
def destroy
@photo.destroy
redirect_to user_photos
end
private
def find_user
@user = User.find(params[:user_id])
end
def find_photo
@photo = Photo.find(params[:id])
end
def photo_params
params.require(:photo).permit(:title, :image, :user_id)
end
end
This is my Users controller:
class UsersController < ApplicationController
def index
@search = User.search(params[:q])
if @search
@users = @search.result.paginate(:per_page => 10, :page => params[:strana])
else
@users = User.all.paginate(:per_page => 10, :page => params[:strana]).order("created_at DESC")
end
end
def new
@user = User.new
end
def create
@user = User.new(user_params)
if @user.save
redirect_to @user
else
render 'new'
end
end
def show
find_params
@photos = @user.photos
end
def edit
find_params
end
def update
find_params
if @user.update(user_params)
redirect_to @user
else
render 'edit'
end
end
def destroy
find_params
@user.destroy
redirect_to users_path
end
This is photos/show view:
<%= image_tag @photo.image.url(:thumb) %>
This is photos/index view:
<% @user.photos.each do |photo| %>
<%= image_tag(photo.image) %>
<%= photo.title %>
<% end %>
Routes are nested:
resources :users do
resources :photos
end
Upvotes: 0
Views: 210
Reputation: 2305
Problem is solved - first images were actually not uploaded (I forgot to add validation) so they had nil value in image link field.
Upvotes: 1