create new object in rails3 using multimodel form

2019-09-16 15:55发布

问题:

I am n00b as rails is concerned. I am trying yo create a single multimodel form in my first rails3 project. Details are given below:

class Item < ActiveRecord::Base
  # attr_accessible :title, :body
  has_many :item_reviews, :dependent => :destroy
  accepts_nested_attributes_for :item_reviews
end

and

class ItemReview < ActiveRecord::Base
  # attr_accessible :title, :body
  belongs_to :item
end

So as clear, an item can have multiple reviews but when I am creating an item, I want at least 1 review for it. So I want to get item and first review in single form while item creation.

I am using following view:

<%provide(:title,'Create')%>
<h1> Add an Item review</h1>

<div class="row">
  <div class="span6 offset3">
    <%= form_for (@item) do |f| %>

      <%= f.label :name %>
      <%= f.text_field :name %>

      <% f.fields_for :item_reviews, @item.item_reviews do |ff| %>
        <%= ff.label :shop_address %>
        <%= ff.text_field :shop_address %>
      <% end %>

      <%= f.submit "Submit", class: "btn btn-large btn-primary" %>

    <% end %>

  </div>
</div>

<% f.fields_for :item_reviews, @item.item_reviews do |ff| %> will not work because there is not item_review associated with @item currently (@item = Item.new) Until I save @item, I can't create new item_review. What should I do in that case.

I know one possibility is model independent form but can't I use something above to make life easy.

PS: I am using bootstrap, just in case if that helps.

回答1:

There is some way to achieve an instance with item reviews. The key is to create an instance with some of nested instances without actual saving

@item = Item.new
@item.item_reviews.build

and then in your form

form_for @item do |f|
...
  f.fields_for :item_reviews do |ff|

with this code an instance of review is present and you can render form