Rails 3 fields_for different layout for existing records/new records, file uploads
I have a Content model which has one or many Audio files which need to be added by the new/edit form. What I have did is created the models with this relationship:
class Audio < ActiveRecord::Base
belongs_to :content
has_attached_file :audiofile,
end
class Content < ActiveRecord::Base
...
has_many :audios
accepts_nested_attributes_for :audios, :allow_destroy => true
end
Now in my n开发者_JAVA百科ew Content form I have the following:
<% f.fields_for :audios do |audiof| -%>
<%= f.label :audiofile, 'Audio file:' %>
<%= audiof.file_field :audiofile %>
<% end -%>
What I need it to do is show me the file_field only for a new Audio file and for the existing ones just print me a file size,name and probably a delete button.
I have also created a new record in the controller with:
@content.audios.build
I am using Rails 3.0.3 with Paperclip plugin for upload. Sorry if the question is too nooby.
Thanks.
From my memory, you will be able to access to the instance of the object within the fields_for statement.
Try something like that :
<% f.fields_for :audios do |audiof| -%>
<% if audiof.object.new_record? %>
<%= f.label :audiofile, 'Audio file:' %>
<%= audiof.file_field :audiofile %>
<% else %>
<%= "Filename = #{audiof.object.audiofile.filename}" %>
<%= "url = #{audiof.object.audiofile.url}" %>
<% end %>
<% end -%>
If audiof.object returns nil(In that case, it is not the good name), check by displaying all the public methods <% = raise audiof.public_methods.inspect %>
The object method should return an instance of an Audio class.
精彩评论