Re: Creating Many Models in One Form

Can you post more of your code?

How are your tables/models structured and related?

Also, post the view code for this form.

Re: Creating Many Models in One Form

here's the relation. click on this link (picture) -> http://i250.photobucket.com/albums/gg268/veil007/db.jpg

here's the print screen image of my addgrade.rhtml. when i click "Add Grade" button, it will create 3 new rows of record in gradebook table in my database.
--> http://i250.photobucket.com/albums/gg26 … DEBOOK.jpg

hope anyone willing to share their knowledge

#FOR def egradebook
<a name="TemplateInfo"></a>
                <h1>E-Gradebook</h1><br>
                <h3> Select Which Class & Subject You Would Like To Update </h3><br>
<%= start_form_tag :action => 'addgrade' %>
<label for = "class1_id">Select Class</label>
<select name="class_1[id]">
<option value="" selected="selected" >Please Select Class</option>
<%@class1s.each do |class1| %>
<option value="<%=class1.id%>"> <%=class1.classname%> </option>
<%end%>
</select><br> <br>


<label for = "subject_id">Select Subject</label>
<select name="subject[id]">
<option value="" selected="selected" >Please Select Subject</option>
<%@subjects.each do |subject| %>
<option value="<%=subject.id%>"> <%=subject.subjectname%> </option>
<%end%>
</select><br><br>

<%= submit_tag "Submit"%>

<%end_form_tag %><br>
--------------------------------------------

#FOR def addgrade
<a name="TemplateInfo"></a>
                <h1>Update E-Gradebook</h1><br>
                <table width="100%" border="0">
  <tr><%=form_tag :action => 'creategrade', :id => @gradebook%>
    <td width="22%"><strong>Class:</strong> <%=params[:class_1][:id]%></td>
    <td colspan="2"><strong>Subject:</strong> <%=params[:subject][:id]%> </td>
  </tr>
  <tr>
    <td><strong>Semester:</strong> <%= text_field 'gradebook', 'semester' , :size => 3 %></td>
    <td width="20%"><strong>Year:</strong> <%= text_field 'gradebook', 'year' , :size => 5 %></td>
    <td width="58%"><label for = "teacher_id"><strong> Select Teacher: </strong></label>
<select name="gradebook[teacher_id]">
<option value="" selected="selected" >Please Select Teacher Name</option>
<%@teachers.each do |teacher| %>
<option value="<%=teacher.id%>"> [<%=teacher.user.id%>] <%=teacher.user.firstname%> <%=teacher.user.lastname%> </option>
<%end%>
</select></td>
  </tr>
  <tr>
    <td>&nbsp;</td>
    <td colspan="2">&nbsp;</td>
  </tr>
</table>
<br>
<table width="100%" border="0">
  <tr>
    <td width="76%"><strong>Student ID & Name </strong></td>
    <td width="12%"><div align="center"><strong>Mark</strong></div></td>
    <td width="12%"><div align="center"><strong>Grade</strong></div></td>
  </tr>
  <tr><%@students.each do |student|%>
    <td>[<%=student.user.id%>] <%=student.user.firstname%> <%=student.user.lastname%></td>
    <td><div align="center"> <%= text_field 'gradebook', 'mark' , :size => 3 %></div></td>
    <td><div align="center"><%= text_field 'gradebook', 'grade' , :size => 3 %></div></td>
  </tr><%end%>
</table>
<div align="center"><br>
    <%= submit_tag "Add Grade" %> <%= end_form_tag %>
--------------------------------------------

def creategrade is the action to save the data into the database

Last edited by veil (2008-02-15 10:22:11)

Re: Creating Many Models in One Form

I'm sorry. I'd love to be able to help you directly, but my suggestion is actually that you take a few steps back and refactor lots of stuff.

Check out the api on the form helpers... especially collection_select:
http://api.rubyonrails.org/classes/Acti … ml#M000941

Also, it's best - if you are going to work with rails - to follow rails conventions. Don't fight it, go with it. For example, in rails, tables have plural names by convention. That's a start.

Check out the api on model associations and the handy methods that get thrown in with each. In your app structure, you have an natural fit for a :has_many :through relationship. A student "has many" classes" through "enrollments" ...and vice versa. I suggest you set it up this way. Create a "students" table with student info, a "classes" table with information about each class, and a join table called "enrollments" which joins a student to a class.

http://api.rubyonrails.com/classes/Acti … ml#M001103

You could then create a "grades" table and associate it with your "enrollments" table. So, again, a "student" would have many "grades" through "enrollments"... and a class would have many grades through enrollments (allowing you to easily average grades by class, for example).

That's my suggestion. It's not going to help you all that much to rush just for the sake of rushing. Dig in... and enjoy it!

Re: Creating Many Models in One Form

how can i dynamically generate the form helper tags? In the sense, how can i make text_field or text_area a variable and generate the form using that variable?

Re: Creating Many Models in One Form

I have been trying to do something very similar.

Take a look at:

http://www.ruby-forum.com/topic/165891

Re: Creating Many Models in One Form

All this is enogh clear now. But recently I got a project for which I have no idea how to create multiple models in one form. The problem that there is a lot of many-to-many relations. And I'm blocked with the last one. So I have 2 tables: Studies and Countries joint as may-to-many via a join table CountryStudies. But the main problem is that this CountryRequirements is joint by many-to-many to an other table - Chemicals via a joint table ChemicalsCountryStudies. So we have something like this:
study.rb

has_many :country_studies
has_many :countries, :through=>:country_studies

country.rb
has_many :country_studies
has_many :studies, :through=>:country_studies

country_study.rb
belongs_to :study
belongs_to :country
has_many :chemicals_country_studies
has_many :chemicals, :through=>:chemicals_country_studies

chemicals_country_study.rb:
belongs_to :country_study
belongs_to :chemicals

chemical.rb
has_many :chemicals_country_study
ha_many :country_studies, :through=>:chemicals_country_studies

I should always start by creating a Study. Chemicals list already exists in the moment of creation. How could I do that. The main information is encoded on Study page. Thanks

Re: Creating Many Models in One Form

Hi
Can someone help me to figure this out...

I have 2 models called Register_record and Attendance.A Register_record has many Attendances.

I have a form which allows user to select the date, and a Register_record will be saved from that date.For that register_record many attendances have to be saved.

class RegisterRecordsController < ApplicationController
  layout'profile'
  def new
    @register_id=@id
    @record=RegisterRecord.new
   
@students=StudentClass.new().get_allstudents_regno(session[:current_class])
   
    @rec_no=@students.size
    @rec_no.times{@record.attendances.build}
  end

For each student in @students array I have to display the name and display a text field to insert attendance in front of the name.

After this we have to save the students name and the corresponding attendance value in Attendances table from the Register_record Id.

I tried to hash the name of student and the attendance value(user input from text field)but didnt work.
Can someone suggest a solution for this.

Thanx

Re: Creating Many Models in One Form

goodnews wrote:

Hi
Can someone help me to figure this out...

I have 2 models called Register_record and Attendance.A Register_record has many Attendances.

I have a form which allows user to select the date, and a Register_record will be saved from that date.For that register_record many attendances have to be saved.

class RegisterRecordsController < ApplicationController
  layout'profile'
  def new
    @register_id=@id
    @record=RegisterRecord.new
   
@students=StudentClass.new().get_allstudents_regno(session[:current_class])
   
    @rec_no=@students.size
    @rec_no.times{@record.attendances.build}
  end

For each student in @students array I have to display the name and display a text field to insert attendance in front of the name.

After this we have to save the students name and the corresponding attendance value in Attendances table from the Register_record Id.

I tried to hash the name of student and the attendance value(user input from text field)but didnt work.
Can someone suggest a solution for this.

Thanx

Hi!
First of all, could you send t stack trace of errors that u have.
Than check your routes. It's not so clear what your models are. Post them too.
Personally whet I have the same situation like something can have O or many things, I first of all put in routes as:

map.resources :register_records , :has_many=> :attendances

Then you attach the show action created by Rails scaffold generato (if u use it) you add a list (or table or whatever u want) of your 'attendances' and a link to add a new one like this:
<%= link_to "Add a attendance", new_register_record_attendance_url(@register_record) %>

Your instance variable will be available from you 'show' action in RegisterRecordController and you just call a new action but this time in AttendancesController.
In you new.htl.erb you declare your form like that:
<% form_for [@register_record, @attendance] do |form| %>
etc...
<%end%>

In your AttendencesController you add:
before_filter :find_register_record, :except => "index"

def new
    @attendance = Attendance.new
  end

  def edit
    @attendance = @register_record.attendances.find(params[:id])
  end

  def create
    @attendance = Attendance.new(params[:attendance])
    if (@register_record.attendances << @attendance)
      redirect_to register_record_url(@register_record)
    else
      render :action => :new
    end
  end
private
  def find_register_record
    id = params[:register_record_id]
    return(redirect_to(register_records_url)) unless id
    @register_record = RegisterRecord.find(id)
  end


Adapt your 'update' method in the same way as 'new'.

Last edited by Javix (2009-02-15 17:31:19)

Re: Creating Many Models in One Form

Hi Javix,
Thanks for your reply.. I dont think I was clear the 1st time. The problem is as follows.

My 2 models are
    1.RegisterRecord
    2.Attendance

class RegisterRecord < ActiveRecord::Base
  has_many :attendances
  belongs_to:register
end

class Attendance < ActiveRecord::Base
  belongs_to :register_record
end

Now I need to save a register record by a 'date' selected by the user. A RegisterRecord belongs to a Register.A Register belongs to class.
In the new action of following code I get all students enrolled in the class to @students array.And I build an 'Attendance' for each student.

class RegisterRecordsController < ApplicationController
  layout'profile'
  def new
    @register_id=@id
    @record=RegisterRecord.new
   
    @students=StudentClass.new().get_allstudents_regno(session[:current_class])
   
    @rec_no=@students.size
    @rec_no.times{@record.attendances.build}
  end

Now the form which is used to save the RegisterRecord has following requirements.

Register Number of student                                  Attendance
==========================                                  =============
012345A   *Taken from @students array                         1# Input from user
012346B                                                       0#
083643H <----I need to merge these 2 values and save them---> 1#

Enter Date :[________]

                                           Submit

I need to create 'one' textfeild for each student.But the following code generates many textfeilds because of the nested for. But I cant figure out any other way also.

<%if @students.blank? %>
                <td class="infoMessage"colspan="2"><center>No students enrolled in this class.                    Make each student enrol for this class..</center></td>
              <%else%>

                     <%form_tag({:controller => "register_records", :action => "create"}, :method => "post") do%>
                     <tr>
                         <%for student in @students  %>
                           <td>

                            <%=label :Reg_number,student  %> </td>
   
                            <%@record.attendances.each_with_index do |attendns,index|%>
                            <% fields_for "attendances[#{index}]", attendns do |f| %>
                           
                           
                            <td >
                           
                            <%= f.text_field :attendance %>
                            <%f.hidden_field:Reg_no,:value=>student%>
                            </td>
                           
                             <% end %>
                    <%end%>
                             </tr>
                             
                     <%end%>

                    <tr>
                      <td colspan="1">
                      Select Date:</td>
                      <td colspan="1">
                        <%= calendar_date_select_tag :Record_date,'click on the icon ' %>
                      </td>
                               
                                <tr>
                                <td  colspan="2"> <%= image_submit_tag("SavecommonButton3Hover.gif" , :align => "right", :height => 25, :width => 59, :border => 0)%></td>  </tr>                    </tr>
                                <%end%>
   

I need to merge the value of attendance to each corresponding student registration number.
One RegisterRecord will be saved with the date.
For the id of that RegisterRecord many Attendances will be saved in attendances table.

class CreateAttendances < ActiveRecord::Migration
  def self.up
    create_table :attendances do |t|
      t.integer :register_record_id
      t.string :registration_no
      t.boolean :attendance

      t.timestamps
    end

class CreateRegisterRecords < ActiveRecord::Migration
  def self.up
    create_table :register_records do |t|
      t.integer :register_id
      t.integer :entered_by
      t.date :record_date
      t.boolean :approval
      t.integer :validated_by

      t.timestamps
    end
  end

Thankx in advance. 

P:S: I tried to create a hash and hash the Student registration number and the attendance value which will be a user input. But I got a hash with only the registration numbers hashed. The attendance values did not get hashed. They remained blank.
And the hash looked something like

{"012345A"=>"","012345A 012346B"=>"","012345A 012346B 083643H  "=>"" }

Re: Creating Many Models in One Form

In your form you call a 'create' action but in your controller you showed me only the 'new' action. What does your 'create' action do?

Re: Creating Many Models in One Form

Hi

Actually I'm hoping to save a RegisterRecord by the date the user input and many Attendances for this RegisterRecord will be saved.
I can't merge the values of Student register number and the corresponding attendance.There for I'm stuck at this point.

def create

@register_record=RegisterRecord.new({"register_id"=>params[:Reg_id],"entered_by"=>session[:user_id],"record_date"=>params[:Record_date]})
if @register_record.save
        flash[:notice] = 'Register Record Successfully saved'
  end
  end

Saving attendances is yet to be implemented.Which is the problem here sad

Re: Creating Many Models in One Form

In your form:

Register Number of student                                  Attendance
==========================                                  =============
012345A   *Taken from @students array                         1# Input from user
012346B                                                       0#
083643H <----I need to merge these 2 values and save them---> 1#

Enter Date :[________]

                                           Submit


It looks like a list of RegisterRecords where every RegisterRecord have a ONE 'record_date'. In your form I can see one and the only one DATE_FIELD.The question is how can you guess for what registerRecord the entered date will be? That's the first.
Second - ONE REgisterRecord have ONE or MANY Attendances. That's why you can't show all the Attendances just in face of one RegisterRecord and that's why you'll have a lot of 'double' lines for the same RegisterRecord(differed in Attendans value only). Technically it's possible by using some JavaScript plugins proposed by jQuery, Mootools, etc.I'd better put a link 'Attendances on the every RegisterRecord line. By clicking on that link you'l get

Re: Creating Many Models in One Form

I am having trouble creating a parent/child single form when using formtastic. Can anyone provide any insight into how to do this?

I am trying to convert my existing code (based on Ryan Bates' railscast - Complex Forms).

A Job has_many Questions.

I am trying to incorporate into the create job form the ability to create some questions at the same time.

#jobs_controller.rb
  def new
    @job = Job.new
    3.times {@job.questions.build}
  end

# jobs/new.html.erb
<% semantic_form_for @job do |f| %>
  <% f.inputs do %>
    <%= f.input :title %>
  <% end %>
 
  <% @job.questions.each_with_index do |q, i| %>
    <% f.semantic_fields_for :question_attributes do |qf| %>
      <% qf.inputs do %>
        <%= qf.input :job_id, :as => :hidden, :value => 'job[id]' %>
        <%= qf.input :question %>
      <% end %>
    <% end %>
  <% end %>
 
  <%= f.buttons %>
<% end %>

In Ryan's cast the submitted objects should take the form
job[question_attributes][][question] but I do not know how to convert them into that array of questions.

Thanks =~ Jeremiah

Re: Creating Many Models in One Form

I had trouble getting this to work, but then I found an example app and was able to learn from it. Here's the link:http://github.com/alloy/complex-form-examples

Highly suggest you guys download and play around with it.