我有一个ContentController,我在这两个动作中执行类似的功能。如何减少这些函数的代码重复?
def like
like = Like.create(like: params[:like], user: current_user, content: @content)
if like.valid?
flash[:success] = "Your vote was successful!"
redirect_to :back
else
flash[:danger]= "You can like a content only once"
redirect_to :back
end
end
def review
review = Review.create(body: params[:body], user: current_user, content: @content)
if review.valid?
flash[:success] = "Your review was successful!"
redirect_to :back
else
flash[:danger]= "You can review a content only once"
redirect_to :back
end
end
答案 0 :(得分:0)
您可以通过这种方式实现它,但请确保您的参数(如/ review)与操作名称相同。
def common_action(action)
object = Object.const_get(action.camelcase).create(action.to_sym => params[action.to_sym])
end