如何在Rails 3中创建一个有效的嵌套表单? (我收到路由错误。)

时间:2010-12-08 05:54:46

标签: ruby-on-rails-3 nested-forms formtastic

我有一个Client和ProposalRequest模型,如下所示:

class Client < ActiveRecord::Base
  has_many :proposal_requests
  accepts_nested_attributes_for :proposal_requests, :allow_destroy => true
end

class ProposalRequest < ActiveRecord::Base
  belongs_to :client

end

在我的路线文件中,我像往常一样包含嵌套路线。

resources :clients do
  resources :proposal_requests
end

到目前为止,这是我的表格:

-semantic_form_for [Client.new, ProposalRequest.new] do |f|
   =f.inputs
   =f.buttons

但在此之后,我因为这个错误而陷入困境。

No route matches {:controller=>"proposal_requests", :client_id=>#<Client id: nil, name: nil, title: nil, organization: nil, street_address: nil, city: nil, state: nil, zip: nil, phone: nil, email: nil, status: "interested", how_you_heard: nil, created_at: nil, updated_at: nil>}

任何人都可以帮我解开这个错误吗?

1 个答案:

答案 0 :(得分:2)

问题是您的嵌套路线是为了向现有ProposalRequest添加新的Client。如果您想同时创建ClientProposalRequest,则需要使用new_client_pathsemantic_form_for @client do |f|

我建议您在clients_controller中执行以下操作:

def new
  @client = Client.find(params[:id])
  @client.proposal_requests.build
end

在你看来:

semantic_form_for @client do |f|      
  = f.inputs # fields for client
  = f.inputs :name => 'Proposal Request', :for => :proposal_requests do |pf|
    = pf.input :some_proposal_request_attribute
  = f.buttons

希望这会有所帮助。请务必查看https://github.com/justinfrench/formtastic处的所有示例,并进行一些试验和错误,以获得您想要的表单。