Search code examples
ruby-on-rails-3virtual-attribute

Assigning multiple form values to one database column


I am newbie to Rails and I cannot seem to find how to assign multiple form values from my view to a single Database column (model attribute). So I tried the virtual attribute approach, here is my code:

My View:

<%= 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 %>

I need to save the codetype and codesnippet values in the same column in my model.

My Schema:

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

My model:

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

Now, I know this is incorrect because my code value gets overwritten by the next virtual attribute. I want to be able to combine the codetype and codesnippet and a few other fields to form a hash and then serialize the hash to make the Database column code. Is there anyway to do this in Rails ?


Solution

  • You can try something like this :

    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