g0nzo wrote:
Hi!
If i have 2 tables i.e. product and images and product has_many images,
image belongs_to product - how to create _form.rhtml, new/create and
edit/update methods in product controller, so in a single form i can add
one product and MANY (let’s assume for now that this number is fixed)
images for this product?
Pleeeeease help me
Here are some snips that worked for me (thanks to the guys here);
CREATE TABLE cvs(
id INT not null AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(30) not null,
family_name VARCHAR(30) not null,
.
.
updated_on timestamp(14) not null
);
drop table if exists skills;
CREATE TABLE skills(
id INT not null AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(20) not null,
detail VARCHAR(200) not null,
cv_id int not null,
created_on timestamp(14) not null,
updated_on timestamp(14) not null,
constraint fk_skills_cv foreign key (cv_id) references cvs(id)
);
The at the command line;
script/generate model CV
script/generate model Skill
(in addition I generated controller & scaffold for each just to get
going;
script/generate controller CV_admin
script/generate controller Skill
script/generate scaffold CV CV_admin
script/generate scaffold skill skills
)
Then edit the 2 models created;
class CV < ActiveRecord::Base
has_many :skills
end
class Skill < ActiveRecord::Base
belongs_to :cv
end
to get the skills to be created from within the CV form;
Skills
<% for skill in @cv.skills %>
<%= h(skill.title) %><%= h(skill.detail) %>
<% end %>
<%= link_to "add_skill", :controller => "skills", :action => "new", :id
=> @cv %>
Inside the skills controller;
def new
@session[:cv_id] = params[:id]
@skill = Skill.new
end
def create
@cv = Cv.find(@session[:cv_id])
@cv.skills << Skill.new(params[:skill])
if @cv.save
flash[:notice] = ‘Skill was successfully created.’
redirect_to :action => ‘show’, :controller => ‘cv_admin’, :id =>
@cv
else
render :action => ‘new’
end
end
the @cv.save updates both the skills list and the cv and takes care of
all the associations for the foreign keys.
good luck.