create new object in rails3 using multimodel form

时光怂恿深爱的人放手 提交于 2020-01-06 19:37:12

问题


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



来源:https://stackoverflow.com/questions/12087735/create-new-object-in-rails3-using-multimodel-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!