HowTo: Virtual Attributes

1) rails howto_use_vitual_attributes

2) cd howto_use_virtual_attributes

3) ruby script/generate scaffold Person first_name:string last_name:string

4) rake db:migrate

5) open up person.rb and add these getter and setter methods


def full_name
[first_name, last_name].join(' ')
end

def full_name=(name)
split = name.split(' ', 2)
self.first_name = split.first
self.last_name = split.last
end

6) edit your new.html.erb file


<%= f.label :full_name %>
<%= f.text_field :full_name %>

Note: full_name is not in the db, it’s just a virtual attribute

7) ruby script/server

8) localhost:3000/people/ (note: not persons :P )

Based on Railscasts ep16.

HowTo: RESTful Autocomplete

rails 2.1

1) rails howto_auto_complete

2) cd howto_auto_complete

3)

ruby script/generate scaffold Tag name:string

4)

ruby script/generate scaffold Post title:string body:text tag_id:integer

5)

rake db:migrate

6) test if it works, add data if you want

ruby script/server

7)

ruby script/plugin install auto_complete

8) in tag controller index replace with this:

@tags = Tag.find(:all, :conditions => ['name LIKE ?', "%#{params[:search]}%"])

9) in posts.rb put these methods:


belongs_to :tag

def tag_name
tag.name if tag
end

def tag_name=(name)
self.tag = Tag.find_or_create_by_name(name) unless name.blank?
end

10) create an index.js.erb in views/tags:

<%= auto_complete_result @tags, :name %>

(restart server to check http://localhost:3000/tags.js)

11) put this in the forms where you want autocomplete (I put mine in edit and new):

<%= text_field_with_auto_complete :post, :tag_name, { :size => 15 }, { :url => formatted_tags_path(:js), :method => :get, :with => "'search=' + element.value" } %>

12) add in layouts/posts.html.erb:

<%= javascript_include_tag :defaults %>

Notes:
-based on Railcasts episode 102
-since post belongs to tag, the postcontroller magically gets/adds the tag name through the set and get methods in #9, the tag_id is still the one saved in posts table

Follow

Get every new post delivered to your Inbox.