如何在保存之前在 Rails 3 中手动设置嵌套模型值?
我有一个文本区域输入,我希望将其作为我的控制器上的 new
方法的 Blob 获取,但希望在保存之前解析输入并以其他方式弄乱输入。
来任意设置模型的属性
@post.user_id = current_user.id
我知道我可以通过说一些属性不直接来自表单的内容 。但我的问题是我想设置嵌套模型的值。
假设关联是 post has_many comments
和 comment own_to post
post.comments
是否只是设置为看起来像评论的哈希值?喜欢
@post.comment = {'comment' => 'foo'}
或类似的东西?
感谢您对此的任何指导。
I have a single text area input that I would like to get as a blob my new
method on my controller, but would like to parse and otherwise mess with the input before it's saved.
I know I can arbitrarily set attributes on a model by saying something like
@post.user_id = current_user.id
where that attribute isn't coming directly from a form. My issue here though is that I want to set a nested model's values.
Let's say the association is post has_many comments
and comment belongs_to post
Does post.comments
just get set to a hash that looks like comments? Like
@post.comment = {'comment' => 'foo'}
Or something similar?
Thanks for any guidance on this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
通常我会说最好干掉这类事情,只用
before_save
回调来处理评论模型本身的解析。但如果回调对您不起作用,@corroded 的建议应该可行。
Usually I'd say it's best to DRY up this sort of thing and just handle the parsing on the comments model itself with a
before_save
callback.But if a callback isn't going to work for you, @corroded's suggestion should work.
如果你有嵌套表单,你可以通过以下方式从你的参数中获取评论值:(
你应该在你的#new中调用@post.build_comment)
如果你想在你的控制器中设置它们,那么你需要一个为您的评论散列“容器”,如下所示:
或类似的内容
if you have nested form fors, you can just get the comment values from your params via:
(you should have called @post.build_comment in your #new though)
If you're looking to set them in your controller, then you need a hash 'container' for your comment like so:
or something like that