如何在保存之前在 Rails 3 中手动设置嵌套模型值?

发布于 2024-11-18 11:05:23 字数 457 浏览 2 评论 0原文

我有一个文本区域输入,我希望将其作为我的控制器上的 new 方法的 Blob 获取,但希望在保存之前解析输入并以其他方式弄乱输入。

来任意设置模型的属性

@post.user_id = current_user.id

我知道我可以通过说一些属性不直接来自表单的内容 。但我的问题是我想设置嵌套模型的值。

假设关联是 post has_many commentscomment 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

能怎样 2024-11-25 11:05:23

通常我会说最好干掉这类事情,只用 before_save 回调来处理评论模型本身的解析。

class Comment < ActiveRecord::Base
  before_save :parse_comment

  protected
  def parse_comment
    self.comment = ...
  end
end

但如果回调对您不起作用,@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.

class Comment < ActiveRecord::Base
  before_save :parse_comment

  protected
  def parse_comment
    self.comment = ...
  end
end

But if a callback isn't going to work for you, @corroded's suggestion should work.

雨后彩虹 2024-11-25 11:05:23

如果你有嵌套表单,你可以通过以下方式从你的参数中获取评论值:(

@post.comment.update_attributes(params[:comment])

你应该在你的#new中调用@post.build_comment)

如果你想在你的控制器中设置它们,那么你需要一个为您的评论散列“容器”,如下所示:

{'comment' => {:message => 'foo', :author => current_user}}

或类似的内容

if you have nested form fors, you can just get the comment values from your params via:

@post.comment.update_attributes(params[:comment])

(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:

{'comment' => {:message => 'foo', :author => current_user}}

or something like that

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文