5

I am still struggling both writing the controller and the actual form to be able to nest one form in another with an optional model?

I have Message which has many contacts

When submitting a message, I want to add a contact optionally.

I have this as an example:

= simple_form_for Message.new, :remote => true do |f|
  #message_form
    = f.error_messages
    %p
      = f.input :account_name, :url => autocomplete_account_name_messages_path, :size => 40, :as => :autocomplete
    %p
      = f.input :topic, :required => true,
                :input_html => {:size => 30}

    #add_contact_btn
      = link_to "Add Contact"

      #contact_form
        = f.simple_fields_for :contactd do |fc|
        = fc.input :email
        = fc.input :first_name
        = fc.input :last_name

    = f.submit 'Give'
    = f.submit 'Request'

For Message.rb model, I have the following:

has_many :contacts
accepts_nested_attributes_for :contacts, :reject_if =>:all_blank

Note: When I used :contacts in the simple_fields_for it didn't work, so it is singular. But the reverse for accepts_nested_attributess_for.

In my create controller for message, I included message.contacts.build

But right now I am still generating nil contacts.

Here is what I see passed as form data from google chrome:

message%5Baccount_name%5D:McKesson
message%5Btopic%5D:testing a contact
message%5Bbody%5D:testing this
sender_id:
receiver_id:23
message%5Bcontacts%5D%5Bemail%5D:888@gmail.com
message%5Bcontacts%5D%5Bfirst_name%5D:Ang
message%5Bcontacts%5D%5Blast_name%5D:Name
4

4 回答 4

8

正确的方法名称是simple_fields_for(注意复数)

此外,您需要保留f.在 simple_form 对象上调用它

于 2011-07-08T19:54:33.630 回答
4

我有一个小项目,我在其中演示了如何结合 cocoon(我创建的用于动态添加/删除嵌套元素的 gem)以简单形式使用嵌套表单。

该项目在github 上

希望这可以帮助。

于 2011-07-14T21:44:43.093 回答
0

我在使用嵌套表单时遇到了类似的问题。正如 JustinRoR 所建议的,您需要定义 attr_accessible:contacts_attributes。

您应该能够在 ruby​​ 控制台中测试哈希(我不确定您是否尝试过)。我建议您打印 params[:message] 并使用它从控制台创建消息,例如 Message.new(params[:message])。(注意 params[:message] 是通过打印 params[:message] 哈希得到的)。

一旦它在控制台中工作,它应该像魅力一样工作

于 2011-07-19T21:15:12.500 回答
0

在我的消息创建控制器中,我包含了 message.contacts.build

但现在我仍然产生零联系。

确保您在 Message.rb 模型中也加入了接受属性的能力。

class Message < ActiveRecord::Base
    attr_accessible :contacts_attributes
    has_many :contacts
    accepts_nested_attributes_for :contacts

我知道它不能完全回答您的问题,但可能就是这样。当涉及到我的项目时,如果我不包括 ,它将返回 nil :contacts_attributes,在我的情况下它处理产品。希望这会有所帮助,即使我现在没有使用简单的形式!

于 2011-07-16T03:04:12.587 回答