Monday 15 April 2013

ruby on rails - Uploading Images through another view -



ruby on rails - Uploading Images through another view -

i using paperclip gem.

class business < activerecord::base has_many :images, :as => :imageable has_many :reviews end class image < activerecord::base belongs_to :imageable, :polymorphic => true has_attached_file :photo end class review < activerecord::base belongs_to :business has_many :images, :as => :imageable end

this works images/_form.html.erb:

<%= form_for @image |f| %> <%= f.fields_for :photos_attributes |photo| %> <%= photo.file_field :image, :multiple => false %> <% end %> <%= f.submit 'save' %> <% end %>

image controller:

def create @image = @business.images.new(image_params) if @image.save flash[:success] = "image uploaded!" redirect_to root_url else render 'new' end end

i want able upload images reviews. i'm thinking this:

<%= form_for @review |f| %> <%= f.text_area :content %> <%= f.fields_for :photos_attributes |photo| %> <%= photo.file_field :image, :multiple => false %> <% end %> <%= f.submit 'submit review image'%> <% end %>

how review controller since image image model , rest review model?

the way lay out -

models

class business < activerecord::base has_many :images, :as => :imageable has_many :reviews end class image < activerecord::base belongs_to :imageable, :polymorphic => true end class review < activerecord::base belongs_to :business has_many :images, :as => :imageable accepts_nested_attributes_for :images end

i've added in accepts_nested_attributes_for :images because need allow review controller save image while saving itself. i'm not sure how have got business controller set advise doing same way, clearer , makes more sense.

review view - form view

<%= form_for @review |f| %> <%= f.text_area :content %> <%= f.fields_for :images |photo| %> <%= photo.file_field :photo, :multiple => false %> <% end %> <%= f.submit 'submit review image'%> <% end %>

i've changed form enable accepts_nested_attributes_for :images work better.

finally review controller

review controller

class reviewscontroller < applicationcontroller def new @review = review.new @review.images.build end def create @business = business.find(id_of_business_your_reviewing) @review = @business.reviews.build(review_params) if @review.save puts "saved" redirect_to "path" else puts "something failed" render 'new' end end private def review_params params.require(:review).permit(:content, :images_attributes => [:id, :photo]) end end

this allow create new review , add together photo through image. there no need go image controller review has access , can take attributes.

i suggest implementing similar business model when creating/editing businesses. have actions performed business controller , utilize accepts_nested_attributes_for :images allow take attributes.

hope helps reply question. allow me know if haven't explained properly.

ruby-on-rails

No comments:

Post a Comment