# Model's code
class Programmer < ActiveRecord::Base
has_one :project_manager
has_many :assignments
accepted_nested_attributes_for :assignments #Rails 2.3+
#Can also used for has_one relation ship
#Can create nested attributes for nested models.
accepts_nested_attributes_for :assignments, :reject_if => proc { |attributes|
attributes['name'].blank? }
#You can also specify requirements for any new records
that are added via nested attributes using the :reject_if option:
end
class assignment < ActiveRecord::Base
belongs_to :programmer
end
#views code
#"programmers/new"
<% form_for @programmer do |f| %>
<%=f.error_messages %> #validates both programmer and assignment model fields
<%= f.label :name %>
<%= f.text_field :name %>
<% f.fields_for :assignments do |assignment| %>
<%= assignment.label :name %>
<%= assignments.text_field :name %>
<% end %>
<%= submit_tag %>
<% end %>
# Controller's code
class programmersController < ApplicationController
def new
@programmer = Programmer.new
@programmer.assignments.build
end
def create
@programmer =Programmer.new(params[:programmer])
if @programmer.save #it autometically saves 'programmer_id 'and fields of
assignments table.
rediretc_to programmers_path
end
end
def update
@programmer = Programmer.find(params[:id])
@programmer.update_attributes(params[:programmer]) ?
redirect_to(programmer_path(@programmer)) : render(:action => :edit)
end
end
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.