开发者

How do I manually set nested model values in Rails 3 before saving?

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 开发者_StackOverflowand 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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜