cool wrote:
I have Person model in that i have used STI like
class person < ActiveRecord
class student <person
class parent < person
for every thing i have table called people.
when i am adding a student i have fields for parent also like
i want to add a student with firstname and last name and at the same
time i mean in the same form i wnat to add to which parent he belongs
to in the same form i have fields like parent name, email, address
This was quite hard to read. Use full stops or bullet points or
something.
can u give idea abt this
So, you have something like
class Person < ActiveRecord::Base …
in app/models/person.rb
And:
class Parent < Person …
class Student < Person …
maybe in app/models/parent.rb and student.rb respectively.
And your ‘people’ table has a column called ‘type’ which is a string
field.
In your edit form you could do something like:
<% form_for :student , :url => {:action => ‘update’} do |s| %>
<%= s.text_field :first_name %>
<%= s.text_field :last_name %>
… parent stuff - see below …
… submit button etc …
<% end %>
Within this form you would have something like:
<%= select :selected_parent , :id ,
Parent.find(:all).collect{|p|[p.last_name,p.id]} %>
which will generate a dropdown with existing parents last_names and
their id’s.
Or if you are entering parents details in alongside the student,
something like:
<%= text_field :parent, :first_name %>
<%= text_field :parent, :last_name %>
Read api.rubyonrails.com and go to ActionView::Helpers::FormHelper and
FormOptions for how to use the form fields and what they generate in
terms of the params your controller will be receiving.
In your controller, the ‘update’ action would do something like:
def update
…
@student=Student.new(params[:student])
@student.parent_id = params[:selected_parent][:id]
@student.save!
(‘parent_id’ is a field for storing the id of the parent in your
‘people’ table.)
You could save the parent using associations instead but I won’t go into
it.
If you were collecting parent details using the text fields above, you
might have:
@parent=Parent.new(params[:parent])
@parent.save!
Daniel