i do some refactoring for my models and want to use "magic" of *delegate* in 
my models.

Have models:

class Asset < ActiveRecord::Base
  has_many :attachments, inverse_of: :asset

  attr_accessible :file
end

which have file attribute. For example needs is file only as string 
attribute.

And Attachment, which is polymorphic and single table inherited. There is 
delegate method for file attribute to asset model.

class Attachment < ActiveRecord::Base
  belongs_to  :attachmentable, polymorphic: true, touch: true
  belongs_to  :asset, inverse_of: :attachments, autosave: true

  attr_accessible :file
  attr_accessible :remove_file, :file_cache

  delegate  :file, :file=, :file?, to: :asset, allow_nil: true

  after_initialize :build_asset_model

  def build_asset_model
    build_asset if self.asset.blank?
  end
end

These 2 models are used to store file and association to between other 
models. So for example we could have:

class Category < ActiveRecord::Base
  has_one :image, as: :attachmentable, dependent: :destroy, autosave: true

  attr_accessible :name, :position
  attr_accessible :image_attributes

  accepts_nested_attributes_for :image, reject_if: :all_blank, allow_destroy: 
true

end

connected with

class Category::Image < Attachment
end

When is is category with image created from console, it works:

cc = Category.new
cc.build_image
cc.name = 'name'
cc.image.file = 'filename.jpg'
cc.save

This works great! Category is created, attachment has polymorphic and STI 
information, asset is created and associated to attachment.

But when is Category saved from front-end html form. It doesn't work, and 
return me, that file attribute is blank. My form:

= simple_nested_form_for @category, html: { class: "form-horizontal" } do |f|
  = render 'shared/error_messages', object: @category

  legend= Category.model_name.human
  = f.input :name
  = f.simple_fields_for :image do |ima|
    = ima.input :file
  .form-actions
    = f.button :submit, :class => 'btn-primary', data: { disable_with: 
t('processing') }
    '
    = link_to t('.cancel', :default => t("helpers.links.cancel")), 
categories_path, :class => 'btn'

controller actions: (using CanCan is automaticaly initialized)

  def new
    # build location
    @category.build_image
    respond_with @category
  end
  def create
    @category.build_image unless @category.image

    @category.save

    respond_with @category
  end

category params

params[:category]
=> {"name"=>"name",
 "image_attributes"=>{"file"=>"filename.jpg"}}

Some help please? Thank you so much.

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msg/rubyonrails-talk/-/wkDMnjByiMIJ.
For more options, visit https://groups.google.com/groups/opt_out.


Reply via email to