Skip to content

Instantly share code, notes, and snippets.

@cyberoctopi
Created April 17, 2012 17:32
Show Gist options
  • Select an option

  • Save cyberoctopi/2407661 to your computer and use it in GitHub Desktop.

Select an option

Save cyberoctopi/2407661 to your computer and use it in GitHub Desktop.
<p>
<%= f.label "Categories" %><br />
<%= f.text_field :category_name, "data-pre" => @product.categories.map(&:attributes).to_json %>
</p>
class Categorization < ActiveRecord::Base
attr_accessor :category_name
belongs_to :product
belongs_to :category
def category_name
category.try(:name)
end
def category_name=(name)
self.category = Category.find_or_create_by_name(name) if name.present?
end
end
class Product < ActiveRecord::Base
attr_accessible :name, :url, :popularity, :views, :description, :category_name
belongs_to :user
has_many :categorizations
has_many :categories, :through => :categorizations
# accepts_nested_attributes_for :categories,
# :reject_if => lambda { |a| a[:content].blank? },
# :allow_destroy => true
## presence of
validates :user_id, :presence => true
validates :description, :presence => true, :length => {:minimum => 140 }
end
<div class="field">
<%= f.fields_for :categorization do |build| %>
<%= render "category_fields", :f => build %>
<% end %>
</div>
def create
@product = current_user.products.build(params[:product])
respond_to do |format|
if @product.save
format.html { redirect_to root_url, notice: '#{current_user.handle}, your product was successfully added, now lets make it famous!.' }
format.json { render json: @product, status: :created, location: @product }
else
format.html { render action: "new" }
format.json { render json: @product.errors, status: :unprocessable_entity }
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment