0

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.

Akash Agrawal
  • 4,711
  • 5
  • 28
  • 26

1 Answers1

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

Vlad Bogomolov
  • 348
  • 4
  • 14
  • Yeah! I agree that an instance of review is present but it's still not rendering. – Akash Agrawal Aug 23 '12 at 09:49
  • got it myself :-> since item_reviews was an array, that was the problem. Fixed it using the advice in http://stackoverflow.com/questions/8271940/form-for-non-ar-model-fields-for-array-attribute-doesnt-iterate – Akash Agrawal Aug 23 '12 at 10:39