开发者

How to grab record id in block within model?

So I have a form that submits some custom attributes for a post. Lets call it "thing_attributes".

Lets also say that I'm 开发者_运维问答posting it from an existing post.

In my Post model I then have the following:

  def thing_attributes=(things)
      mybook = Book.new      
      mybook.title = things
      mybook.post_id = ?
  end

My actual code is more complicated - so I realize this seems asinine, but it makes sense in my execution.

Either way, as you can see I have no idea how to get that post_id in there, from the post that the form is being submitted from.

Any ideas?


If that's being set on an existing post (say, an edit form), then you can just call

id or self.id

But maybe a better way would be to do this:

class Post < ActiveRecord::Base
  has_many :books # and book belongs_to :post

  def thing_attributes=(things)
    self.books.create(:title => things)
  end
end

And the post_id should automatically be set for you.


If Post has_many books, and Book belongs_to :post, then:

post.books.build

should be used instead of:

Book.new

and it will set the post ID for you, since it's an association.

Otherwise, since thing_attributes is an instance method of Post, self.id will return the current post's ID.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜