Rails: 图片上传站点。主页

Rails: Image Uploading Site. Home page

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 加载了一张已显示的照片。然后当您单击 next/previous 时,您将被路由到 www.example.com/photos/#{photo_id}

如何让我的网站执行此操作?我还想设置它,以便每天在主页上显示一张不同的随机照片。

如果要在首页显示随机照片,需要满足以下条件:

#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

参考文献:

  • (适配器)
  • (随机)

--

这将允许您在 indexshow 操作中填充 @phooto 变量;

#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 %>

您将能够解决剩下的问题。


关于每 渲染一张新的随机图像,您必须在每次日期变化时存储 "random" 值。

最好使用 cron job, invoking a rake task:

#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