What are the edit and new actions doing in this code?
I have three models:
class Country < ActiveRecord::Base
has_many :regions
has_many :assets, :dependent => :destroy
accepts_nested_attributes_for :assets
end
class Region < ActiveRecord::Base
belongs_to :country
has_many :appartments
has_many :assets, :dependent => :destroy
accepts_nested_attributes_for :assets
end
class Asset < ActiveRecord::Base
belongs_to :region
belongs_to :country
has_attached_file :image,
:styles => {
:thumb=> "100x100开发者_运维知识库>",
:small => "300x300>",
:large => "600x600>"
}
end
Can some explain to me what the edit and new method/action is of the region controller, to store the asset(image)?
Here is an example of how you could do it by building your form in a certain way. It should work for both the new and update actions.
<%= form_for @region do |f| %>
<%= f.fields_for :assets, @region.assets.build do |fa| %>
<%= fa.file_field :image %>
<% end %>
<% end %>
What this does is to first create the form for the @region instance. And since you have the accepts_nested_attributes_for :assets
you can use the fields_for
method to work with the associations. The symbol :assets
tells it which association to read from, but since you want to add a new image and not work with the existing, you can add the second argument which is a single new Asset instance created by the build
method.
And then finally you can add the file_field
to actually upload the file.
If you build your form this way you should not have to alter the action code inside your controller at all.
Edit:
And here is how the new
and create
actions could look like to make the view work:
def new
@region = Region.new
# Add respond_to or respond_with if you want
end
def create
@region = Region.new(params[:region])
if @region.save
render :action => :show
else
render :action => :new
end
end
精彩评论