开发者

Rails editing an Image attached to a model

I'm trying to set up a model (client) that contains some general attributes about a company but also has a company logo attached. I'm reluctant to use a plugin because I want to grasp this aspect of rails if possible.

I've created a clients model and an image model and I can create a new client (scaffold code) and upload an accompanying image ok (using has_one :image, and belongs_to :client).

I used the following code (taken straight from Agile Rails 3rd ed)

class Client < ActiveRecord::Base
  has_one :image

  def uploaded_image=(image_file)
    self.image = Image.new
    self.image.name = base_part_of(image_file.original_filename)
    self.image.content_type = image_file.content_type
    self.image.data = image_file.read
  end

  def base_part_of(filename)
    File.basename(filename).gsub(/^\w_-/,'')
  end

end

when editing the client object however, the new file is uploaded but the changes aren't reflected in the db. Do I need to explicitly call update-attributes on @client.image? At the moment my controller update method is as follows:

def update
  @client = Client.find(params[:id])

  respond_to do |format|
    if @client.update_attributes(params[:client])
      f开发者_如何转开发lash[:notice] = 'Client was successfully updated.'
      format.html { redirect_to(@client) }
      format.xml  { head :ok }
    else
      format.html { render :action => "edit" }
      format.xml  { render :xml => @client.errors, :status => :unprocessable_entity }
    end
  end
end

Thanks in advance for any tips, apologies for the noob question


I would strongly recommend to use Paperclip instead. It just works.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜