我已经开发了一个管理页面的代码,在ruby on rails上有crud。但我怀疑。这段代码可以以任何方式改进吗?除了设计模式,良好实践等。
另外,我确实将管理控制器类中的crud操作分开了。这被认为是一种很好的做法吗?或者有什么方法可以进一步改善它?谢谢。
# app/controllers/game_controller.rb
class GameController < ApplicationController
def create
Game.create(game_params)
end
def update
game = Game.find(params[:id])
if (game.update_attributes(game_params))
return true
end
return false
end
def read
game = Game.find(params[:id])
end
def delete
if (Game.find(params[:id]).destroy)
return true
else
return false
end
end
private
def game_params
params.require(:game).permit(:description,:name,:category,:status,:boxshot)
end
end
# app/controllers/admin_controller.rb
class AdminController < ApplicationController
before_action :require_logged_in_user
before_action :define_action
def index
@games = Game.all
@admin = get_admin_details()
end
def read
render :json => @action.read
end
def update
if (!@action.update)
render :text => "false"
end
render :text => "true"
end
def delete
if(!@action.delete)
render :text => "false"
end
render :text => "true"
end
def logout
reset_session
redirect_to(:controller => 'login', :action => 'view')
end
private
def define_action
@action = GameController.new()
@action.params = params
I18n.locale = cookies['language']
end
def get_admin_details
admin = User.find(require_logged_in_user())
end
def require_logged_in_user
if(session[:user_id])
return session[:user_id]
else
redirect_to(:controller => 'login', :action => 'view')
end
end
end
答案 0 :(得分:3)
老实说,有一点可以改进。这是我对GameController
class GameController < ApplicationController
before_action :find_game, only: [:update, :show, :delete]
def new
@game = Game.new
end
def create
@game = Game.new(game_params)
if @game.save
redirect_to game_path(@game)
else
render :new
end
end
def edit
end
def update
if @game.update(game_params)
redirect_to game_path(@game)
else
render :edit
end
end
def show
end
def delete
if @game.destroy
redirect_to games_path
else
render :show
end
end
private
def find_game
@game = Game.find(params[:id])
end
def game_params
params.require(:game).permit(:description, :name, :category, :status, :boxshot)
end
end
我需要一些时间来更彻底地学习Rails的基础知识。查看Railscasts。它比较旧,但仍然很好。任何高级剧集都可以在Youtube上找到。
您还可以查看样式指南并使用他们提供的建议。
无论你做什么,最重要的是保持一致。保持相同的缩进量,相同的类结构,相同的赋值和条件结构等。
要回答第二个问题,您需要为每个新CRUD操作设置一个新控制器。不要试图将大量的功能装入一个控制器中。保持简单,线条便宜。