Sunday 15 May 2011

How to save relationship when creating an entity with Ruby on Rails -



How to save relationship when creating an entity with Ruby on Rails -

it seems learnt ruby on rails dissapeared mind.

i trying create simplest relationship ever, between products , categories. defined has_many :categories relationship in product model, , created migration have table product_id , category_id.

first, thought passing parameters product.new automatically add together categories. recall worked this.

then tried doing manually: @product.categories = product_params[:categories]. product_params generated scaffold, , follows:

def product_params params.require(:product).permit(:title, :description, :categories) end

however, doing way, @product.categories seems nil.

how can store product_id , category_id (or categories, since has many relationshop) in relationship table? have been looking @ old codes of mine ruby on rails 3 , seems handled automatically rails. missing?!

`product` model: class product < activerecord::base has_and_belongs_to_many :categories, :join_table => 'products_categories' accepts_nested_attributes_for :categories end

class="snippet-code-html lang-html prettyprint-override"># product.rb class product < ar::base has_and_belongs_to_many :categories end #products_controller.rb def new @product = product.new end def create @product = product.new product_params @product.save end private def product_params params.require(:product).permit(:product, :attributes, :category_ids => []) end end

and within view:

class="snippet-code-html lang-html prettyprint-override"><%= form_for @product |f| %> <%=f.select :category_ids, options_for_select(category.all.collect {|c| [c.name, c.id] }, @product.category_ids ), {}, :multiple => true %> <% end %>

ruby-on-rails ruby-on-rails-4

No comments:

Post a Comment