如何在模型中的块中获取记录ID?

时间:2011-04-04 01:39:22

标签: ruby-on-rails ruby ruby-on-rails-3

所以我有一个表单为帖子提交了一些自定义属性。让我们称之为“thing_attributes”。

让我们说我是从现有的帖子发布的。

在我的Post模型中,我有以下内容:

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

我的实际代码更复杂 - 所以我意识到这似乎是在asin,但它在我的执行中是有意义的。

无论哪种方式,正如您所看到的那样,我不知道如何从提交表单的帖子中获取post_id。

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

如果在现有帖子(例如编辑表单)上设置,那么您只需致电

idself.id

但也许更好的方法是做到这一点:

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

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

并且应该自动为你设置post_id。

答案 1 :(得分:0)

如果Post has_many books,并且book belongs_to:post,则:

post.books.build
应该使用

代替:

Book.new

它会为你设置帖子ID,因为它是一个关联。

否则,由于thing_attributes是Post的实例方法,self.id将返回当前帖子的ID。