Update params in 2 models

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???

Thanks
Kostas

I have used something like this but it does not works:
@current_teacher.update_attributes(:last_project_created=>params[:code])

If this isn’t working, the first place I’d look is in params[:code].
What’s in that at the time this runs ?

Also don’t forget you could use update_attribute in a situation like
this eg:
@current_teacher.update_attribute(:last_project_created, params[:code])

update_attributes iterates over each key in the hash and calls
update_attribute on it, so you’re saving rails a step or 2.

Kostas L. 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

Hello to both!

@Luke: I finally used the following:
@current_teacher.update_attribute(:last_project_created,
@project.code)
that worked fine!

@Peter: i think your sollution is much better and i will try it when i
finish my project that i’m working on! :))

Kostas