I'm working in Rails 4/Ruby 2.0.0. I have a two models - Articles
and Graphics
. Articles
has_many
Graphics
. So, in my code I am trying to add an empty record to the graphics collection on the article so that in the form, there will be an empty set of fields to let a new record be added. I cannot figure out why the fields do not show up on the form though.
I've tried multiple methods of building the graphics collection but none seem to do the trick. Surely I must be missing something insanely small.
class Article < ActiveRecord::Base
has_many :graphics, :dependent => :destroy, :foreign_key => 'article_id'
accepts_nested_attributes_for :graphics,
:allow_destroy => true,
:reject_if => :all_blank
end
class Graphic < ActiveRecord::Base
belongs_to :article
validates_presence_of :path, :caption
end
...
<% f.fields_for :graphics do |g| %>
<div class="clear clearfix pad-b-20">
<div class="w-1-2 left f-left">
<div class="field">
<%= g.label :path %><br>
<%= g.text_field :path %>
</div>
</div>
<div class="w-1-2 left f-left">
<div class="field">
<%= g.label :caption %><br>
<%= g.text_field :caption %>
</div>
</div>
</div>
<% end %>
...
<%= form_for(setup_article(@article)) do |f| %>
module FormHelper
def setup_article(article)
article.graphics.build
article
end
end
...
after_initialize :build_graphics
private
def build_graphics
self.graphics.build
end
...
def new
@article = Article.new
@article.graphics.build
end
...
The problem is that both for form_for
and for fields_for
you need to use <%=
, because they render the contents of the form.
So, to solve your problem, you need to write
...
<%= f.fields_for :graphics do |g| %>
Your content
<% end %>
...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.