Kostas Lps wrote in post #976857:
Hi there,
i have a form with some fields where i put info about a university
project like "name","title","code" etc.
I create this project successfully but i want to update a specific
attribute from the model teacher too. I have a field in there with the
name "last_project_created" and i want to update it with the "code"
parameter from this form.
I have used something like this but it does not works:
@current_teacher.update_attributes(:last_project_created=>params[:code])
I put this line into the create method after the @project.save line.
Any ideas what i can do???
I would put the foreign key in the projects table.
Assuming a teacher has many projects then I would do:
* define a has_many from teacher to project
* define an association that _automatically_ calculates
the most recently created project by a teacher
* also define the belongs_to in the Project class and use that
when creating the new project.
(caveat: code not tested)
class Teacher
...
has_many :projects
has_one :most_recently_created_project, :class_name => "Project",
:order
=> "created_at DESC"
...
end
class Project
...
#makes lists of projects always predictable order
default_scope :order => "created_at DESC"
belongs_to :teacher
...
end
This would allow you to say:
in the controller:
@project = Project.new(params)
@project.teacher = @current_teacher
if @project.save
# success
else
# retry
end
later on:
#all projects by this teacher
teacher.projcts
#calculate most recent project of this teacher
teacher.most_recently_created_project
HTH,
Peter