【发布时间】:2016-12-19 23:35:52
【问题描述】:
我不完全确定 Rails 中私有方法的概念,以及何时以及如何使用它。有什么规则吗?私有与公共与受保护之间有什么区别?例如,在下面的示例中,为什么这里使用私有方法而不是其他两种方法。始终对用户生成的输入使用私有方法是最佳做法吗?请赐教。非常感谢!
class PostsController < ApplicationController
def index
@posts = Post.all.order("created_at DESC")
end
def new
@post = Post.new
end
def create
@post = Post.new(post_params)
if @post.save
redirect to @post
else
render 'new'
end
end
def show
@post = Post.find(params[:id])
end
private
def post_params
params.require(:post).permit(:title, :body)
end
end
【问题讨论】:
-
Ruby on Rails Web 应用程序是使用 Ruby 编程语言编写的。
private的概念来源于 Ruby 本身,Rails 并没有给它添加任何特殊含义。 Ruby 从面向对象编程(OOP)领域得到了public和private的概念。因此,我建议您只需查找 OOP 中的 public 和 private 是什么意思,并将 Rails 排除在您的搜索之外。
标签: ruby-on-rails