我正在尝试在rails scaffold示例中使用ruby。
我将ruby version: 2.1.5
与rails version : 4.1.8
我使用过这个命令:
rails generate scaffold User name:string email:string
这很好用 - 我可以运行一个示例,它向我生成的脚手架显示crud功能。我一直在遵循的示例建议查看生成的模型文件。示例中的那些似乎有一个名为attr_accessible的值 - 但对我来说这不是生成的 - 我不知道为什么 - 它似乎非常有用,所以你可以很容易地看到你的模型里面有什么?我的模型看起来像这样:
class User < ActiveRecord::Base
end
我改变它看起来像这样:
class User < ActiveRecord::Base
attr_accessible :name, :email
validates :name, :presence=>true
end
当我现在访问localhost / users时出现错误:
有人可以告诉我如何使用此attr_accessible行创建生成的模型,以及如何向模型添加验证示例。
答案 0 :(得分:4)
Rails 4不使用attr_accessible
;它使用 Strong Parameters 。
他们都是params
批量转让的守卫,通常在提交表格时使用。
据我所知,脚手架不支持自动设置强对数,部分原因是人们以非常不同的方式实施强烈的params白名单。
关于Strong Params的更多链接
对我而言,这表明你所遵循的任何指南都已过时。
答案 1 :(得分:1)
我认为问题在于您使用的脚手架与Rails在更高版本中的工作方式不兼容。在早期版本的Rails中,attr_accessible
用于防止与批量分配相关的安全问题。在更高版本中,对策已更改并移至控制器而非模型。
如果您仍想使用attr_accessible
宏,则可以将gem 'protected_attributes'
添加到Gemfile
并使用捆绑包进行安装。
答案 2 :(得分:-2)
您不应该在模型中添加它们。 你想访问的东西会进入控制器,比如
def index
@users = User.all
end
def show
@user = User.find(params[id])
end
...
private
def user_params
# It's mandatory to specify the nested attributes that should be whitelisted.
# If you use `permit` with just the key that points to the nested attributes hash,
# it will return an empty hash.
params.require(:user).permit(:name, :mail)
end
因此您可以在视图中使用它们。
e.g。在app / views / users / show ...
<h1>@user.name</h1>
<p>@user.email</p>