2016-06-08 39 views
0

我有一个student模型与字段:name, :address可能的钢轨形式字段?

我想创建2个不同的字段:country, :city,填写并提交时,将连接到address db字段。

怎么办?我必须在student.rb中定义一些东西吗?或者只是一些表单视图?

我的学生/ _form.haml:

= simple_form_for @student do |f| 
    = f.input :name 
    = f.input :country #not in db 
    = f.input :city #not in db 
    = f.button :submit 

(地址必须等于country + " " + city

注:我不想创建国家&城市独立数据库字段。

回答

0

可以在模型做它在以下方面

  1. 化妆地址 - >这是最好的方式控制
  2. 化妆地址 - >这是很好的方式

way no 1 in model

attr_accessor :country 
attr_accessor :city 

def before_save 
    self.address = @country + " " + @city 
end 

在控制器

def save 
    student = Student.new() 
    student.country = params[:country] 
    student.city = params[:city] 
    student.save 
end 

路2号 例如模范学生,在控制器

def save 
    student = Student.new 
    student.address = params[:country] + " " + params[:city] 
    student.save 
end 

我希望它可以帮助学生控制 。