SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Enthusiast
    Join Date
    Jun 2006
    Posts
    45
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Joining Fields in a Select

    Hey all,

    Does anyone know if you can join fields in a drop down box in ruby?

    For example, in the database Firstname and Lastname are stored in separate columns, can they be joined so that the full name is displayed in the drop down box in a ruby form?

    Cheers,

  2. #2
    SitePoint Guru
    Join Date
    Aug 2005
    Posts
    986
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code:
    class Person < ActiveRecord::Base
      # ...
      
      def full_name
        first_name + ' ' + last_name
      end
    end
    
    # ...
    
    @person = Person.find(1)
    @person.full_name # => "ABC XYZ"

  3. #3
    SitePoint Enthusiast
    Join Date
    Jun 2006
    Posts
    45
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks for the reply,

    Any idea on how I can render this in a form as a drop down list? I have tried a few things and I cant figure out how to combine them.

    Cheers

  4. #4
    SitePoint Enthusiast
    Join Date
    Apr 2007
    Posts
    70
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Will this work for you?

    Code:
    class CreateDatabases < ActiveRecord::Migration
     
      def self.up
        #...
    
        create_table :people do |t|
            t.column :first_name, :string, :limit => 20, :null => false
            t.column :last_name, :string, :limit => 20, :null => false
        end
        #...
      end
    
      def self.down
         #...
    
         drop_table :people
    
         #...
      end
    
    end
    Code:
    class PeopleController < ApplicationController
      # ...
    
      def list
         @all_persons = Person.find(:all, :order=>"last_name")
      end
    
      #...
    end
    Code:
    class Person < ActiveRecord::Base
      # ...
    
      def full_name
         last_name + ', ' + first_name
      end
    
      #...
    end
    View would contain :
    Code:
    <%= collection_select(:person, :id, @all_persons, :id, :full_name) %>


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •