本文介绍了使用多模型形式在 rails3 中创建新对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
就 rails 而言,我是 n00b.我正在尝试在我的第一个 rails3 项目中创建一个单一的多模型表单.详情如下:
class Item :破坏accepts_nested_attributes_for :item_reviews结尾
和
class ItemReview
很明显,一个项目可以有多个评论,但是当我创建一个项目时,我希望它至少有 1 个评论.所以我想在创建项目时以单一形式获取项目和第一次评论.
我正在使用以下视图:
<h1>添加商品评论<div class="row"><div class="span6 offset3"><%= form_for (@item) 做 |f|%><%= f.label :name %><%= f.text_field :name %><% f.fields_for :item_reviews, @item.item_reviews 做 |ff|%><%= ff.text_field :shop_address %><%结束%><%= f.submit "Submit", class: "btn btn-large btn-primary" %><%结束%>
<% f.fields_for :item_reviews, @item.item_reviews 做 |ff|%>
将不起作用,因为当前没有与 @item
关联的 item_review (@item = Item.new
) 直到我保存 @item,我才能'不创建新的 item_review.这种情况我该怎么办.
我知道一种可能性是与模型无关的形式,但我不能使用上面的东西来简化生活.
PS:我正在使用引导程序,以防万一.
解决方案
有一些方法可以实现带有项目评论的实例.关键是创建一个带有一些嵌套实例的实例,无需实际保存
@item = [email protected]_reviews.build
然后在你的表单中
form_for @item do |f|...f.fields_for :item_reviews 做 |ff|
使用此代码,存在审查实例,您可以渲染表单
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.
解决方案
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
这篇关于使用多模型形式在 rails3 中创建新对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!