Rails 3——在隐藏表单字段中传递 user.id 与使用关联
好的,目前我有一个表单
<div class="field">
<%= f.label :title %><br/>
<%= f.text_field :title %><br/>
<%= f.label :itunesurl %><br />
<%= f.text_field :itunesurl %><br />
<%= f.hidden_field :user_id, :value => current_user.id %>
</div>
<div class="actions">
<%= f.submit %>
</div>
,它将 current_user.id 传递到我的“app”模型的创建方法中,该方法在保存之前像这样创建它:
@app = App.new(params[:app])
但是我有(伪代码)的关联
user has_many apps
apps belongs_to user
问题:它更安全吗(所以表单不没有被修改)在创建方法中执行类似的操作?
@user = current_user
@app = @user.apps.create(params[:app])
如果是这样......我到底该如何实际实现上面的代码(它在语法上不正确......只是伪)?
谢谢!
Ok so currently I have a form
<div class="field">
<%= f.label :title %><br/>
<%= f.text_field :title %><br/>
<%= f.label :itunesurl %><br />
<%= f.text_field :itunesurl %><br />
<%= f.hidden_field :user_id, :value => current_user.id %>
</div>
<div class="actions">
<%= f.submit %>
</div>
Which passes the current_user.id into the create method of my "app" model which creates it like this before saving it:
@app = App.new(params[:app])
However I have associations of (pseudocode)
user has_many apps
apps belongs_to user
Question: is it safer (so the form doesn't get modified) to do something like this within the create method?
@user = current_user
@app = @user.apps.create(params[:app])
If so... how exactly would I go about actually implementing the code above (its not syntactically correct.. just pseudo)?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,使用您建议的第二种方法是最好的方法
另外,请确保保护自己免受大规模分配的影响,请阅读此http://stephenscafani.com/2010/01/04/ruby-on-rails-secure-mass-assignment/
Yes using the second way that you have suggested is the best approach
Also make sure you protect yourself from mass assignment, take a read of this http://stephensclafani.com/2010/01/04/ruby-on-rails-secure-mass-assignment/
采用第二种方法绝对更安全。如果您采用第一种方式,您就相信客户会说出自己的身份。任何人都可以轻松修改表单(使用 firebug,或者他们可以使用许多工具手动提交
POST
请求)并最终使用另一个人的current_user
提交表单。确保在整个应用程序中的任何地方都应用这种思想。永远不要相信客户提交的任何内容。
It's absolutely safer to do it the second way. If you do it the first way, you're trusting the client to state who they are. Anyone could easily modify the form (with firebug, or they could manually submit a
POST
request with many tools) and end up submitting a form with thecurrent_user
of another person.Make sure you apply this thinking everywhere throughout your app. Do not trust anything the client submits, ever.
第二个代码片段比第一个代码片段更加“RESTful”。我所说的更加 RESTful 的意思是,如果应用程序是通过用户逻辑访问的资源,那么一定要使用它。
通过路由进行设置的方式:
这将为您提供诸如 user_app_path 和 new_user_app_path 之类的路径,您可以向其中传递用户 ID 和应用 ID 或新应用。
希望这有帮助
The second code snippet is more "RESTful" than the first. By more RESTful, I mean, if an App is a resource that is logically accessed through a User, then by all means use it.
The way you set that up through routes:
This will give you paths like user_app_path and new_user_app_path, to which you pass a user ID and an app ID or a new app.
Hope this helps