【问题标题】:How to grab record id in block within model?如何在模型中的块中获取记录 ID?
【发布时间】:2011-04-04 01:39:21
【问题描述】:

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

还可以说我是从现有帖子中发布的。

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

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

我的实际代码更复杂 - 所以我意识到这看起来很愚蠢,但在我的执行中是有意义的。

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

有什么想法吗?

【问题讨论】:

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


    【解决方案1】:

    如果这是在现有帖子(例如,编辑表单)上设置的,那么您可以调用

    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。

    【讨论】:

    • 谢谢你!这很完美(使用顶级解决方案,因为我正在工作的东西非常复杂 - 但关于第二个解决方案的信息很好!) - 当它让我在 5 分钟内将其标记为正确
    【解决方案2】:

    如果 Post 有_many 本书,并且 Book 属于_to :post,那么:

    post.books.build
    

    应该用来代替:

    Book.new
    

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-07
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      相关资源
      最近更新 更多