2016-06-08 50 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 

我希望它可以幫助學生控制 。