将多个表单值分配给一个数据库列

时间:2013-05-22 20:32:54

标签: ruby-on-rails-3 virtual-attribute

我是Rails的新手,我似乎无法找到如何将多个表单值从我的视图分配到单个数据库列(模型属性)。所以我尝试了虚拟属性方法,这是我的代码:

我的观点:

<%= form_for @userinfo do |f|%>
<%= f.label :name %> :
<%= f.text_field :name %><br/> 

<%= f.label  "URL or IP" %>:
<%= f.text_field :URL %> <br> 

<%= f.label "codetype" %>:
<%= f.text_field :codetype %> <br>

<%= f.label "codesnippet" %>:
<%= f.text_field :codesnippet %> <br>

<%= f.submit %>

我需要将codetype和codesnippet值保存在模型的同一列中。

我的架构:

create_table "UserInfo", :force => true do |t|
t.string   "name"
t.string   "URL"
t.string   "code"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end

我的模特:

class UserInfo < ActiveRecord::Base
  attr_accessible :URL, :name,  :codetype, :codesnippet
  validates :name, :presence => true
  validates :URL, :presence => true
  validates :name, :format => { :with => /\A[a-zA-Z]+\z/,
   :message => "Only letters allowed" }


    def codetype=(codetype)
      self.code = codetype 
    end

    def codetype
    end

    def codesnippet
    end

    def codesnippet=(codesnippet)
      self.code = codesnippet
    end
end

现在,我知道这是不正确的,因为我的代码值会被下一个虚拟属性覆盖。我希望能够将codetype和codesnippet以及一些其他字段组合起来形成一个哈希,然后序列化哈希以生成数据库列代码。无论如何在Rails中这样做?

1 个答案:

答案 0 :(得分:0)

您可以尝试这样的事情:

class UserInfo < ActiveRecord::Base
  attr_accessible :URL, :name,  :codetype, :codesnippet, ;code
  validates :name, :presence => true
  validates :URL, :presence => true
  validates :name, :format => { :with => /\A[a-zA-Z]+\z/, :message => "Only letters allowed" }

  def code
    codetype + '-' + codesnippet   #suppose you are joining both values with a hiphen in between
  end

  def code=(codetype, codesnippet)
    self.code = codetype + '-' + codesnippet
  end

end