新来的铁轨。在一篇关于多态关联的教程之后,我偶然地看到了在创建和销毁中设置@client。
@client = Client.find(params[:client_id] || params[:id])我通常只习惯于只能找到@client = Client.find(params:id)
那么,,这是如何工作的,有两个对角?是如何工作的?
FavoriteClientsController.rb:
class FavoriteClientsController < ApplicationController
def create
@client = Client.find(params[:client_id] || params[:id])
if Favorite.create(favorited: @client, user: current_user)
redirect_to @client, notice: 'Leverandøren er tilføjet til favoritter'
else
redirect_to @client, alert: 'Noget gik galt...*sad panda*'
end
end
def destroy
@client = Client.find(params[:client_id] || params[:id])
Favorite.where(favorited_id: @client.id, user_id: current_user.id).first.destroy
redirect_to @client, notice: 'Leverandøren er nu fjernet fra favoritter'
end
end控制器的完整代码,模型可以看到这里
使用rails 5
发布于 2017-01-27 11:38:53
表达式:params[:client_id] || params[:id]与:
if params[:client_id]
params[:client_id]
else
params[:id]
end发布于 2017-01-27 12:17:22
哇,这是一种非常糟糕的做法。
对多态子级执行控制器的一个非常可扩展和干净的模式是使用继承:
class FavoritesController < ApplicationController
def create
@favorite = @parent.favorites.new(user: current_user)
if @favorite.save
redirect_to @parent, notice: 'Leverandøren er tilføjet til favoritter'
else
redirect_to @parent, alert: 'Noget gik galt...*sad panda*'
end
end
def destroy
@favorite = @parent.favorites.find_by(user: current_user)
redirect_to @parent, notice: 'Leverandøren er nu fjernet fra favoritter'
end
private
def set_parent
parent_class.includes(:favorites).find(param_key)
end
def parent_class
# this will look up Parent if the controller is Parents::FavoritesController
self.class.name.deconstantize.singularize.constantify
end
def param_key
"#{ parent_class.naming.param_key }_id"
end
end然后我们定义子类:
# app/controllers/clients/favorites_controller.rb
module Clients
class FavoritesController < ::FavoritesController; end
end
# just an example
# app/controllers/posts/favorites_controller.rb
module Posts
class FavoritesController < ::FavoritesController; end
end然后,您可以使用以下命令创建路由:
Rails.application.routes.draw do
# this is just a routing helper that proxies resources
def favoritable_resources(*names, **kwargs)
[*names].flatten.each do |name|
resources(name, kwargs) do
scope(module: name) do
resource :favorite, only: [:create, :destroy]
end
yield if block_given?
end
end
end
favoritable_resources :clients, :posts
end最终的结果是一种基于OOP的可定制模式,而不是“聪明”的代码。
发布于 2017-01-27 11:39:43
教你如何做的教程
Client.find(params[:client_id] || params[:id])是一个超级错误的教程:)我强烈建议您切换到另一个。
回到主题:这是合乎逻辑的:如果第一个表达式既不是nil也不是false,则返回它,否则返回第二个表达式。
https://stackoverflow.com/questions/41893106
复制相似问题