#185
Oct 26, 2009

Formtastic Part 2

Learn about some of the more advanced functionality of Formtastic including handling many-to-many associations, required fields, and styling.
Download (19.7 MB, 9:11)
alternative download for iPod & Apple TV (12.6 MB, 9:11)

Resources

script/generate nifty_scaffold problem name:string
rake db:migrate
script/generate nifty_scaffold symptom animal_id:integer problem_id:integer --skip-controller
script/plugin install git://github.com/redinger/validation_reflection.git
# models/animal.rb
class Animal < ActiveRecord::Base
  attr_accessible :name, :category_id, :born_on, :female, :problem_ids
  belongs_to :category
  has_many :symptoms
  has_many :problems, :through => :symptoms
  validates_presence_of :name, :born_on
end

# models/problem.rb
class Problem < ActiveRecord::Base
  attr_accessible :name
  has_many :symptoms
  has_many :animals, :through => :symptoms
end

# models/symptom.rb
class Symptom < ActiveRecord::Base
  attr_accessible :animal_id, :problem_id
  belongs_to :animal
  belongs_to :problem
end

# config/initializers/formtastic_config.rb
Formtastic::SemanticFormBuilder.inline_errors = :none
/* formtastic_changes.css */
form.formtastic fieldset ol li p.inline-hints {
  font-style: italic;
  font-size: 11px;
}
<!-- views/animals/_form.html.erb -->
<% semantic_form_for @animal do |f| %>
  <%= f.error_messages %>
  <% f.inputs do %>
    <%= f.input :name, :hint => "Use the owner's name if none is provided" %>
    <%= f.input :born_on, :start_year => 1900 %>
    <%= f.input :category, :include_blank => false %>
    <%= f.input :female, :as => :radio, :label => "Gender", :collection => [["Male", false], ["Female", true]] %>
    <%= f.input :problems, :as => :check_boxes, :required => false %>
  <% end %>
  <%= f.buttons %>
<% end %>

RSS Feed for Episode Comments 46 comments

1. Marc Bowes Oct 26, 2009 at 00:05

Thanks Ryan, been waiting for this!


2. Brunagh Oct 26, 2009 at 00:18

Many Thanks!
I was expecting this episode since last week :)


3. badboy_ Oct 26, 2009 at 00:42

great! exactly what I need for my current project.

thanks Ryan!


4. Samuel Tonini Oct 26, 2009 at 00:58

Just great, thanks Ryan! :)


5. grimen Oct 26, 2009 at 01:05

Nice one Ryan! I recommend you all to checkout the Formtastic I18n features, they are very flexible. Not only useful for internationalization, but also usability. Peep the README. =)


6. Joost Saanen Oct 26, 2009 at 01:14

Very nice one, Ryan. Was waiting a week for this one :) Keep up the good work


7. Frederic Oct 26, 2009 at 02:03

One small typo in the models/symptom.rb file: the symptom belongs to an :animal, not an ":animial" :-)

Thanks a lot Ryan for all of your screencasts.


8. Marian André Plösch Oct 26, 2009 at 02:04

Really good episode!! I love Monday mornings with a new Railscasts episode ;)


9. waqas Oct 26, 2009 at 02:15

Hi ryan. Once again grt screencast. I love it and going to use it on me next small rails project.


10. Todd MIller Oct 26, 2009 at 02:30

Great episode. In episode 63, you discussed permalinks. If you're using some name as opposed to the id number for seo, is it possible to use formtastic and how would you do that?


11. luciano Oct 26, 2009 at 04:58

Hello Ryan!
I could not find a better way to start my weeks than watching your railscasts!
Congratulations!
Luciano


12. cbmeeks Oct 26, 2009 at 07:01

Awesome as usual but do you think you could put a better spam filter on your site?

There are tons of spam posts in your comments.

Keep up the great work!


13. Ryan Bates Oct 26, 2009 at 07:07

@Frederic, thanks for mentioning the typo, fixed now.

@Todd, Formtastic is not tied to the URL, so you are free to use a permalink instead of an id in there and it won't conflict.

@cbmeeks, planning to solve the spam problem soon, thanks!


14. Wayne Molina Oct 26, 2009 at 07:28

And I was just looking for Formtastic tutorials when I stumbled upon this. Great as usual, Ryan!


15. Alex Reisner Oct 26, 2009 at 08:27

Formtastic is great, but if you don't want your forms so tightly linked to your models, check out the Informant plugin/gem:

http://github.com/alexreisner/informant


16. DGM Oct 26, 2009 at 08:37

Love it! I was just wondering about many to many relationships. I just have one question: what about when the list is too large to put in a list box or check boxes?

For example, I have a large database of names and phone numbers, and people can share phone numbers and also have many different phone numbers. Some sort of autocomplete and ajax addition would be interesting.


17. Carl Oct 26, 2009 at 09:31

One thing I'd love to see is what if your symptoms model had been a full fledged model with additional attributes that couldn't be placed on either of the joined models? Say it had a "cured_on" attribute for when that particular problem was cured. How would you handle that?


18. Timóteo Bica Oct 26, 2009 at 09:31

How to build a form without a model linked to it? It can be done with this gem?


19. DGM Oct 26, 2009 at 10:51

Oh, and one other thought, what about adding a new symptom/problem that doesn't exist yet? I think you did a railscast on adding a has_many like that, but how about a many-to-many?


20. Martin Oct 26, 2009 at 13:13

Thanks Ryan. As usually your great tutorial helped me shave off those precious hours!


21. Justin French Oct 26, 2009 at 19:53

@DGM Formtastic there's a plugin for Formtastic that does auto complete, but IMHO, focusing on what Formtastic can't do is the wrong attitude, because you would've had to write all that code anyway. In the meantime, it's done _everything else_ for you :)

It's very easy to mix-and-match Formtastic code with custom ERB code or even make your own custom inputs (which I do all the time) to solve specific problems.


22. Justin French Oct 26, 2009 at 19:56

@Timóteo Formtastic is built on top of Rails' built in FormBuilder, so yes, it's very much tied to forms that have models. However, it's important to point out that it will work with *any* model or class that behaves a little bit like an ActiveRecord object.

A good example of this is AuthLogic, which has a UserSession model that isn't an ActiveRecord model, but there are plenty of people that have built login forms that work with the UserSession model and Formtastic.


23. Justin French Oct 26, 2009 at 20:01

@Jamie the CSS file included is, more than anything, a proof-of-concept. If you want labels on top, go for it, it's a few lines.

Eventually I'd like to offer both, because different situations will call for either a side-by-side layout or a labels-on-top layout. I'd be sceptical of any study that makes a claim that either approach is "always more usable".

I think someone's working on a formtastic-sass plugin too which does both styles.


24. Bruno Cotteret Oct 27, 2009 at 07:54

Hi! Formtastic is very cool !
And good screencast (as usual!) :)
@justin:
Is there any helper like remote_form_for in Formtastic ?
Best regards,
Bruno


25. activestylus Oct 27, 2009 at 16:35

For anyone who uses haml/sass, you can get multiple form layouts (labels on top, left or right) for free using a simple sass sheet.

http://github.com/activestylus/formtastic-sass


26. Daryl Oct 27, 2009 at 18:49

Thanks for this! I was interested about formtastic since I first heard about it on RailsEnvy podcast a few weeks ago.

Any chance there's a third part planned to cover more has_many :through topics? Personally creating new records, auto complete and additional relationship fields have always trouble me.

But again, thanks for the awesome intro to formtastic!


27. Alan Maciel Oct 28, 2009 at 06:55

There is a way to use formtastic to handle multiple models in one form like the Ryan's Classic Recipe?


28. Michael Kastner Oct 28, 2009 at 23:52

Great one, as usual!

However, what if you have to deal with complex multi column forms?

Seems I'm getting spoiled ...


29. james Oct 29, 2009 at 04:09

I am getting

The requested URL /videos/185_formtastic_part_2.mov was not found on this server.

Looking forward to watching:)


30. Arcath Oct 29, 2009 at 05:31

The link doesnt seem to be working...

i get a 404 message when i try to download the video


31. Zach Oct 29, 2009 at 07:28

There seems to be a problem with the podcast when subscribing from itunes.
non of the files seem to be on the server:

for example it says this file can't be found on the server, and for that matter none of them can.

http://media.railscasts.com/videos/185_formtastic_part_2.m4v


32. andhapp Oct 29, 2009 at 11:28

Update: the latest gem would copy the formtastic.rb file to config/initializers and you don't have to create one by hand.


33. David Nov 01, 2009 at 14:05

Nice that you added CAPTCHA to prefend spam. But now i can not help you with spam reports because of authorized error message.

Thanks for your create screencasts!

Cu


34. Mr Frosti Nov 03, 2009 at 14:38

When using model associations (@user.posts), @post.categories, etc), you can order the options by using the :collection parameter:

<% semantic_form_for(@user) do |f| %>
  <% f.inputs do %>
    # Posts is an association to users
    <% f.posts, :collection => Post.all(:order => :name) %>
  <% end %>
<% end %>


35. vesters Nov 05, 2009 at 01:51

Is there any explanation as to why we need to use 'attr_accessible' on all attributes in the model? Seems like a lot of work...


36. Holger Nov 06, 2009 at 13:49

Any ideas how i get the code from the complex forms railscasts to work with formtastic ?

How would that project example look in formtastic ?

  <% for task in @project.tasks %>
    <% fields_for "project[task_attributes][]", task do |task_form| %>
      <p>
        Task: <%= task_form.text_field :name %>
      </p>
    <% end %>
  <% end %>


37. flaubert Nov 07, 2009 at 10:03

great stuff! so, what about dynamic select boxes?? still by hand?


38. ciihla Nov 16, 2009 at 06:14

Hi, nice screencast!
Do you happen to know if the formtastic handles acts_as_tree plugin in association has_many :through? For example: I want to have check_boxes in the form like as tree structure..(Like categories and subcategories in eshop).
Thank you,

H.


39. pixelated_dwarf Nov 19, 2009 at 00:26

Trying to recreate this with HAML but can't get it to work can you give me the basic form?


40. hendri Nov 20, 2009 at 23:42

great tutorial from the great plugin, very nice, thanks for 2 great episode about formtastic. but i got a problem when i use paperclip, attr_accessible can't be used, because paperclip use attr_protected. whould you like to tell me about this situation ?, or give me a link about attr_protected to read ?. sorry my english is bad...


41. Robert Dec 04, 2009 at 19:26

Thank you very, very much for this. I was stuck on forms for 5 hours today trying to do a multi-select on a has many through. When I couldn't figure it out I said "f it. Railscasts will have a better solution". 30 minutes later, everything works perfectly. Thank you very much!

Robert


43. yeni müzik Dec 29, 2009 at 15:47

This is one of those "clever" solutions that will only cause


44. pduersteler Jan 18, 2010 at 06:08

Thanks for this one, Ryan!

A third part would be nice, like in complex forms 3, where you add/remove checkboxes dynamically ;-)


45. pduersteler Jan 18, 2010 at 23:48

@carl

See the formtastic rdoc, there's an example for nested forms ;-)


46. Manolo Blahnik Jan 24, 2010 at 23:05

Trying to recreate this with HAML but can't get it to work can you give me the basic form?


47. cheap adidas shoes Jan 31, 2010 at 19:15

Adidas Shoes Online Shop-Hot Selling Adidas Shoes & Cheap Adidas Shoes

Add your comment:

(SKIP THIS ONE)

(required)

(not shown)


(use pastie or gist for code)

sponsored by:
if you want to help:
required:
Get Quicktime Player
Give Back to Open Source