Rails 3后续表单提交(第二个依赖于第一个)

时间:2011-07-26 09:25:43

标签: ruby-on-rails-3

我正在努力实现后续的表单提交。澄清事情 -

  • 我提交@post
  • 的表格
  • 然后,一旦创建@post,我会立即(在引擎盖下)提交@associations的表单。
  • 问题是,第二次表单提交需要新创建的@post的post_id字段。

实现这一目标的最佳方法是什么?嵌套表单会帮我拉新创建的@ post.id吗?请帮助我。

1 个答案:

答案 0 :(得分:1)

如果这是在您创建Post时应该发生的事情,那么您应该使用活动回调来实现:

class Post < ActiveRecord::Base

  after_create do |post|
    # create your association using post.id
  end

end

或者,您也可以这样写:

class Post < ActiveRecord::Base

  after_create :after_create_post

  def after_create_post
    # create your association using self.id
  end

end

否则,如果这是控制器动作特有的,那么你应该简单地做这样的事情:

class PostsController < ApplicationController

  def create
    @post = current_user.posts.build(params[:post])
    # then use the @post.id to build your association. something like
    @post.associations.build(:prop1 => 'value1', :prop2 => 'value2')
  end

end

希望这有帮助!