#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 50 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


42. 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 ;-)


43. pduersteler Jan 18, 2010 at 23:48

@carl

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


44. Livecam Mar 18, 2010 at 11:57

Great Screencast i love ruby. Formtastic I18n is fantastic! Thank you very much!


45. pgg May 05, 2010 at 06:00

Thanks for this Ryan and all the other great casts you have done.

Have you managed to get this excellent gem to work with Rails3, I cant seem to get rid of the undefined method semantic_form_for error


46. Stretch Marks May 10, 2010 at 00:28

This is really a very nice post. And yes I liked the comments too.


47. Jeff Klein May 16, 2010 at 03:43

Nice script.I have another similar script also.Let me try this..... :)


48. buy gps May 17, 2010 at 19:37

I am finding something like this.And now it is end in your post thnx.


49. Hp ipaq May 17, 2010 at 19:39

Nice post buddy.One of the great tutorial.

Thnx


50. Colon Cleanse May 17, 2010 at 23:47

Thank you very much for the information. It's new for me and it is a very knowledgeable post. Thanks for sharing with us.


51. Alex Graven Jun 17, 2010 at 14:14

And how do you do unit tests? If you have a partial which is one of these semantic_form_for, how the blazes do you run renderizer so that it works, hm?

No unit testing examples, no TDD. Pity.


52. How To get Pregnant Jun 22, 2010 at 01:23

This is one of the best posts that I’ve ever seen; you may include some more ideas in the same theme. I’m still waiting for some interesting thoughts from your side in your next post.


53. acai berry supplements Jul 01, 2010 at 01:50

awesome post,i just bookmark it.


54. facebook sexbook Jul 06, 2010 at 06:06

I like to build without a model linked to it


55. internet and computer Jul 06, 2010 at 08:27

I like your posting, thanks


56. Internet Marketing Product Reviews Jul 09, 2010 at 12:50

thanks guys


57. fat burning furnace Jul 16, 2010 at 07:37

Thanks Ryan. A very interesting read. Good job.


58. iPhone Ringtone Maker for mac Jul 20, 2010 at 18:43

thank you for sharing the post


59. Greg Jul 26, 2010 at 01:44

Just to share with you, as I have spent plenty of hours figuring that. It is useful to have datepicker in date field. I have found a nice gist by @voldy. On http://blog.brzezinka.eu/webmaster-tips/ruby/ruby-on-rails-formtastic-jquery-ui-datepicker I show how to integrate jQuery UI datepicker with Ruby on Rails Formtastic gem.


60. Testking 1Y0-A05 Jul 28, 2010 at 00:58

thats really very good..


61. fat burning furnace Aug 02, 2010 at 06:29

thanks for the screen saver


63. logo design Aug 08, 2010 at 23:52

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


64. glue gun Aug 09, 2010 at 00:47

Nice post! Although we are familiar with our culure, but we maybe don't really understand it. It need to study deeply.


64. Jeff Smith Aug 10, 2010 at 08:46

Great job here guys. Keep the great posts coming. I follow your blog and I follow you on Twitter.


65. error fix Aug 13, 2010 at 18:15

Not only useful for internationalization, but also usability. Peep the README. =)


66. authentic nike shoes Aug 19, 2010 at 22:42

Nice post! Thanks Ryan. A very interesting read. Good job. Although we are familiar with our culure, but we maybe don't really understand it.


67. Wholesale baseball hats Aug 20, 2010 at 20:21

Took me awhile to read all the comments, but I really love the article. It proved to be very useful to me and I am sure to all the commenters here! It's always nice when you can not only be informed, but also entertained! I'm sure you had fun writing this article. Comfortably, the article is really the sweetest on this precious topic.


68. PDF to Images Converter Aug 24, 2010 at 23:10

Some times, to a certain need, we have to convert PDF to image for enjoyment.


69. Wholesale Electronics Aug 25, 2010 at 01:31

Discount Wholesale Electronics, Wholesale Cell Phones, Electronic Gadgets and More from the Best Dropship Wholesaler


70. louis vuitton shoes Aug 26, 2010 at 23:14

Thanks for sharing your article. I really enjoyed it. I put a link to my site to here so other people can read it. My readers have about the same interets


71. movie blog Aug 26, 2010 at 23:50

The beauty of these blogging engines and CMS platforms is the lack of limitations and ease of manipulation that allows developers to implement rich content and 'skin' the site in such a way that with very little effort one would never notice what it is making the site tick all without limiting content and effectiveness.


72. Tutorial Blog Aug 27, 2010 at 01:26

This is a smart blog. I mean it. You have so much knowledge about this issue, and so much passion. You also know how to make people rally behind it, obviously from the responses. Youve got a design here thats not too flashy, but makes a statement as big as what youre saying. Great job, indeed.


73. snow boots Aug 30, 2010 at 20:44

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


74. louis vuitton sunglasses Sep 01, 2010 at 21:42

Good post, I can’t say that I agree with everything that was said, but very good information overall:)

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