I have a model Aulas wich has a tokenfield for the model Courses. When I save the Aula, I want to extract the name of the Course in the token and save into the name of the Aula, is that possible? So instead of "aula.course.name" I can have the same name on "aula.name"
Models
class Aula < ActiveRecord::Base
attr_accessible :name,:course_tokens
has_many :menagements
has_many :courses, :through => :menagements
attr_reader :course_tokens
def course_tokens=(tokens)
self.course_ids = Course.ids_from_tokens(tokens)
end
end
class Course < ActiveRecord::Base
attr_accessible :aula_id, :name
has_many :menagements
has_many :aulas, :through => :menagements
def self.tokens(query)
courses = where("name like ?", "%#{query}%")
if courses.empty?
[{id: "<<<#{query}>>>", name: "New: \"#{query}\""}]
else
courses
end
end
def self.ids_from_tokens(tokens)
tokens.gsub!(/<<<(.+?)>>>/) { create!(name: $1).id }
tokens.split(',')
end
end
And the controler
def create
@aula = Aula.new(params[:aula])
respond_to do |format|
if @aula.save
format.html { redirect_to @aula, notice: 'Aula was successfully created.' }
format.json { render json: @aula, status: :created, location: @aula }
else
format.html { render action: "new" }
format.json { render json: @aula.errors, status: :unprocessable_entity }
end
end
end
I tried:
def do_something_before_save
self.name = self.courses.each do
end
and i get
--- - !ruby/object:Course attributes: id: 1 name: Extra 2B aula_id: 11 created_at: 2013-03-08 13:26:15.806995000 Z updated_at: 2013-03-14 19:58:53.542650000 Z
but I try this, and it shows the same result
def do_something_before_save
self.name = self.courses.each do |course|
course.name
end
The info is there, I just don´t seem to get it. The part I want is Extra 2B
You can add a before_save
callback which will trigger a method before saving Aula
class.
Something like:
class Aula < ActiveRecord::Base
...
before_save :do_something_before_save
def do_something_before_save
self.name = self.course.name
end
...
end
I fugured that because it is an Array, I should specify the one course I want to show the info, so I did
def do_something_before_save
self.name = self.courses.first.name
end
first is to specify the one course I want the info.
Thanks for the help.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.