我有一个模型 Aulas,它有一个模型课程的标记字段。保存Aula的时候,我想把token中Course的名字提取出来保存到Aula的名字里,可以吗?所以代替“aula.course.name”我可以在“aula.name”上使用相同的名字
楷模
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
和控制器
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
我试过:
def do_something_before_save
self.name = self.courses.each do
end
我明白了
--- - !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
但我试试这个,它显示了相同的结果
def do_something_before_save
self.name = self.courses.each do |course|
course.name
end
信息就在那里,我只是不明白。我想要的部分是Extra 2B