【问题标题】:How do I use a single form in a view for a multiple-models in Rails 3?如何在 Rails 3 中的多个模型的视图中使用单个表单?
【发布时间】:2011-03-23 16:20:46
【问题描述】:

我只有一个表格。

该表单当前位于模型消息的视图中。

有时,我希望能够将联系人(名字、姓氏)与该特定消息相关联。联系人是它自己的模型。

提交表单时,Message 有一个contact_id 属性。我希望该contact_id 被关联,但也希望创建一个新的联系人。

如何在 Rails 3 中做到这一点?

【问题讨论】:

    标签: ruby-on-rails forms


    【解决方案1】:

    您似乎希望从同一个表单创建 Contact 和 Message 对象并将它们关联起来。正如我在上一个问题中告诉你的那样。 form_for 既可以取独立值,也可以取其他对象值。

    _form.html.erb

    <% form_for :message do |f| %>
      <%= f.test_field :some_field %>
      ..
      ..
      <%= text_field :contact, :first_name %>
      <%= text_field :contact, :last_name %>
      <%= f.submit %>
    <% end %>
    

    messages_controller.rb

    def new
      @message = Message.new
      @contact = Contact.new
    end
    
    def create
      @message = Message.new(params[:message])
      @contact = Contact.new(params[:contact])
      @contact.message = @message
      if @contact.save # saves both contact and message if has_one relation is given in models
        ..
      else
        ...
      end
    end
    

    不过话说回来,还是用嵌套表单模型比较好。为此,您必须编写以contact 为中心的代码。

    contacts_controller.rb

    def new
      @contact = Contact.new
      @contact.message.build
    end
    
    def create
      @contact = Contact.new(params[:contact])
      if @contact.save
        ..
      else
        ..
      end
    end
    

    _form.html

    <% form_for :contact do |f| %>
      <% f.fields_for :message do |p| %>
        <%= p.text_field :some_field %>
        ...
      <% end %>
      <%= f.text_field :first_name %>
      <%= f.text_field :second_name %>
      <%= f.submit %>
    <% end %>
    

    为此,您必须在 Contact.rb 中指定 accepts_nested_attributes_for :message

    【讨论】:

    • 谢谢...我不确定是否要嵌套它们,因为例如,与一条消息关联的联系人可能会在另一条消息中提供给其他人...但是如果我创建has_one(我假设我必须将message_id属性传递给contact_id)我只需要保存@contact就是我所期待的......听起来对吗?
    • 是的..如果您的contact.rb中有has_one :message,那么当您提供@contact.message = @message并保存@contact.save时,联系人对象和消息对象将保存到数据库中,同时将消息中的contact_id 保存为新保存的contact 记录的id。所以,你只需要@contact.save
    【解决方案2】:

    使用嵌套模型表单。

    看看: http://asciicasts.com/episodes/196-nested-model-form-part-1

    它基于 Rails 2,但为了使代码与 Rails 3 兼容,没有太多工作要做。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-17
      • 1970-01-01
      • 1970-01-01
      • 2018-09-11
      相关资源
      最近更新 更多