سؤال

I have two models post and sign like this.

class Post < ActiveRecord::Base
  has_many :signs
  accepts_nested_attributes_for :signs
end

class Sign < ActiveRecord::Base
  belongs_to :post
end

And I use nested_form gem, and this is form for post

<%= nested_form_for(@post) do |f| %>
  ...
  <%= f.fields_for :signs do |sign| %>
  <%= render 'sign_fields', :f => sign %>
  <% end %>
  ...
<% end %>

And this is _sign_fields.html.erb.

<div class="sign">
    <%= image_tag "#{"%02d" % @post.signs[f.options[:child_index].to_i].image_number}.jpg" %>
</div>

It works though, I think there is a better way than @post.signs[f.options[:child_index].to_i].image_number.

How can I access the attributes of child model?

هل كانت مفيدة؟

المحلول

You can use

f.object.image_number
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top