views:

82

answers:

2

I have a "category" table that contains different kind of "product", so I create this in the category.rb:

class Category < ActiveRecord::Base
  has_many :products
end

And this in product.rb:

class Product < ActiveRecord::Base
  belongs_to :categories
end

I would like to know how can I get the :categories From the product in the products/new.html.erb.... ....

Happy New Year!

+3  A: 

EDIT: Simplified code

I recommend that you use Formtastic which will do it automatically for you. If you want to do it rails without Formtastic, solution is:

Assuming you are using partial for new.html.erb and edit.html.erb, the code will go into _form.html.erb

<%= f.label :category_id %><br />
<%= f.collection_select :category_id, Category.all, :id, :name%>
Chandra Patni
You need to make sure that `Product` model has `category_id` field and `products` table has the `category_id` column as well. You can run the following command in a new project to see the code.`script/generate scaffold Product name:string category_id:integer`
Chandra Patni
I see, I added the productId in there, it works, thx u. But it shows the actual category_id instead of the category_name. Here is my code:<% semantic_form_for @category do |f| %> <%= f.input :category, :include_blank => false %> <%= f.buttons %> <% end %>
Ted Wong
one more follow up, after I use this, the validate become crazy, I have several validate in my product.rb, after I input some data, it will treat me no input at all. what happen? I am using ruby script/generate migration add_category_id_to_product category_id:integer to add the category_id.
Ted Wong
Can you rephrase your question? Also if it's require code, then you may want to post a new question where it's easy to provide you code snippets.
Chandra Patni
A: 

Check out these Railscasts about complex (nested) forms and formtastic:

makevoid