class PhootosController < ApplicationController
before_action :logged_in_user
def index
@phootos = Phooto.all.sample(1)
end
def new
end
def show
@phooto = Phooto.find(params[:id])
end
def create
@phooto = current_user.phootos.build(phooto_params)
if @phooto.save
flash[:success] = "Photo created!"
redirect_to uploads_url
else
redirect_to root_url
end
end
def favorite
@phooto = Phooto.find params[:id]
if request.put?
current_user.favorites << @phooto
redirect_to :back, notice: 'You successfully favorited #{@phooto.name}'
elsif request.delete?
current_user.favorites.delete(@phooto)
redirect_to :back, notice: 'You successfully unfavorited #{@phooto.name}'
else
redirect_to :back, notice: 'Nothing happened.'
end
end
def feed
@favorites = current_user.favorites.all
end
def uploaded
@phootos = current_user.phootos.all
end
private
def phooto_params
params.require(:phooto).permit(:picture)
end
end
show.html.erb
<p><strong>Picture:</strong></p>
<%= image_tag(@phooto.picture) %>
<%= link_to("< Previous", @phooto.previous) if @phooto.previous %>
<%= link_to("Next >", @phooto.next) if @phooto.next %>
<% if current_user %>
<%= link_to "favorite", favorite_phooto_path(@phooto), method: :put %>
<%= link_to "unfavorite", favorite_phooto_path(@phooto), method: :delete %>
<% end %>
www.example.com/photos/1
专业网站在主页www.example.com上加载已显示的照片。然后,当您单击下一个/上一个时,您将被路由到www.example.com/photos/#{photo_id}
如何让我的网站执行此操作?我也想要它设置,以便每天在主页中显示不同的随机照片。
答案 0 :(得分:0)
如果要在首页上显示随机照片,则需要以下内容:
#config/routes.rb
resources :photos, only: [:index, :show]
#app/controllers/photos_controller.rb
class PhotosController < ApplicationController
def index
random = ActiveRecord::Base.connection.adapter_name == 'MySQL' ? "RAND()" : "RANDOM()"
@phooto = Photo.order(random).first
end
def show
@phooto = Photo.find params[:id]
end
end
参考文献:
-
这样您就可以在@phooto
和index
操作中填充show
变量;
#app/views/photos/index.html.erb
<%= render @phooto %>
#app/views/photos/show.html.erb
<%= render @phooto %>
#app/views/photos/_photo.html.erb
<p><strong>Picture:</strong></p>
<%= image_tag(photo.picture) %>
<%= link_to("< Previous", photo.previous) if @phooto.previous %>
<%= link_to("Next >", photo.next) if @phooto.next %>
<% if current_user %>
<%= link_to "favorite", favorite_phooto_path(phooto), method: :put %>
<%= link_to "unfavorite", favorite_phooto_path(phooto), method: :delete %>
<% end %>
你能够解决剩下的问题。
关于每个天呈现新的随机图像,您必须存储&#34;随机&#34;每次变化时的价值。
#lib/tasks/new_random.rb
namespace :random do
task :generate => :environment do
# save random for the day (maybe in a model or redis)
end
end