#196 Nested Model Form Part 1
Handling multiple models in a single form is much easier with the accepts_nested_attributes_for method. See how to use this method to handle nested model fields.
- Download:
- source code
- mp4
- m4v
- webm
- ogv
Thanks Ryan. Very goog job!
Can I suggest another screencast related to this one?
I really appreciate something like this with MongoMapper?
The surveys sample fits very well with the concept of a document database.
Is it possible?
Thank you very much.
I've heard this can work somewhat for has many through, but I've not seen a concrete example. Is that what part 2 might be?
Thanks for this Ryan, looking forward to this series.
As it happens I am near completion of a survey website in which I am making use of nested model forms.
I came across a painful bug in the version of rails which I am using (2.3.4):
Check boxes used for data entry (e.g. a boolean value in my model) cause the hashes in params to be split for nested models when the user ticks them.
For example I have a form which includes a nested model called "CourseOffering".
When the user does not tick any check boxes the params hash includes a course_offerings_attributes hash which itself contains one hash for each course offering (as you would expect).
When they do tick a check box, that particular course offering gets split into two different hashes, this causes various problems depending on validation rules.
The only way I was able to overcome this problems was to use select boxes instead.
I hope I have explained this clearly enough - I think it's something to watch out for!
Nested model forms are really helpful, I use them right now to add some generic attributes to different models with a has_one relationship. I am wonder how to add these javascript add / remove links though, it seemed not so easy last time I searched for a solution.
using latest nifty_generators, in the survey model i see the following, but it's not in the railscast:
attr_accessible :name
unless i comment this out, cannot edit questions/answers
Does accepts_nested_attributes_for work well with virtual attributes?
As always, excellent Ryan. I've been a heavy user of the complex forms method, this looks way smarter.
Thanks Ryan! Can't wait Part 2 ;) BTW what is the TextMate plugin you use for creating partials? I can't find one working. Same thing with the one putting links to TextMate when an error occurs, couldn't make it work (this is a Rails plugin, not a TM).
Awesome timing. I just had to do this in a project and wasn't 100% sure I was doing it properly. This just confirmed it for me!
Thanks!
Hello Ryan,
Thank you for yet another awesome cast!
BTW, how are you filling the forms with a touch/click? Which plugin/tool are you using for that?
Thank you!
Paddy
Great stuff Ryan!
Try looking into LowPro for Prototype to create a nested behavior JS class (andd/remove links). It makes your JS code very reusable (http://bit.ly/76dDzz) and there is a version of LowPro for jQuery. And if anyone cares, RightJS comes with most of the functionality built in ;)
Superb. You have raised the screencast quality bar to a new level.
I really love how your increasing mastery of the art is expressed by the emergence of a subtle humor: the finger snap, the answer to the universe... I follow your casts to learn, obviously, but beyond pure information I find them enjoyable because of the sense of being spoken to directly. I'm so impressed.
It's amazing how often these screencasts come out just as I'm trying to figure out how something works.
Specifically, the reject_if was something I was wondering how to implement for today. Thanks for saving me a few hours! :-)
lambda? what was that?
Would it be possible in a future show to also give an example of how to ask questions that are dependent on the answer. Like: if answer == 2
then ask these 4 questions, etc.?
Thanks.
Great Screencasts!!!!
-Luis.
Something wrong with cancan? Your "Report as Spam" links don't work anymore and opening them in a new window gives me a "Not authorized to access this page." message.
If I may suggest a cast topic: could you do a cast on testing models with associations and sessions? I find this really troublesome. My app works, but a lot of tests fail, because some objects turn out to be nil. I have nailed this down to sessions not working so well. I have found a snippet of yours in some forum, but this doesn't help. Well, it did help, but sometimes it doesn't. Very strange...
Last, but not least: Thanks for all those great screencasts. :-)
This is a great update to one of my most-referenced railscasts! So glad to see the multiple nesting and how much easier it has become in Rails 2.3!
Does anyone know if formtastic supports nested models?
Yes, formtastic supports nested models.
It's in the documentation.
http://github.com/justinfrench/formtastic
Interesting. I was unable to get this functionality working in formtastic.
I'll try again, mimicing Ryan's code.
Thanks!
Exactly what I needed, exactly when I needed it. Thanks, Ryan. Looking forward to Part Deux.
Will you do a railscast about the plugin you use for the snapping of the fingers? :)
P.S. This cast is my favourite! Can't wait until next week.
Thank you Ryan for another series of screencasts!
Hopefully this time you will cover long-awaited validation in deeply nested forms.
Thanks a MILLION,
Boris
You are amazing Ryan! I was just bashing my head in the other day wondering how to pull this off with my controllers spazzing out at one another. Not the best task for a newb.
It's trippy how you always seem to find what I need at the right time.
Thanks
I guess it's not _destroy but _delete. The _destroy was not working for me and I looked at railsbrain.com and it was actually _delete.
http://railsbrain.com/api/rails-2.3.2/doc/index.html?a=M002182&name=accepts_nested_attributes_for
really nice tutorial, looking forward for part two. Also interested in deleting and sorting elements using js
Thanks Ryan! Great tutorial, as I was struggling in a project with many nested models.
For some reason, I can't get this to work:
:reject_if => lambda { |a| a[:content].blank? }
It simply won't save the questions to the database. Anyone else having that issue?
If I remove it, the questions are saved but blank ones are saved as well - just as in the screencast prior to adding that line to Ryan's controller.
Ah, it seems to be an issue with passing in the content as a symbol. If I do it like this it works fine:
:reject_if => lambda { |a| a['content'].blank? }
Can anyone help me understand why?
@Chris Lerum you need to do give the nested_attribute free:
attr_accessible :questions_attributes
Great screencast, Ryan. I found myself using the Complex Form series quite a lot in my work. I am loving passing these as attributes so easily.
I did wonder about a TextMate-ism in your railscast. I noticed once you made your partial you were able to start at "builder." and select up to builder on multiple lines and then used a key combo to select only "builder" in order to change all instances to "f". Is that a custom item in a bundle or is it available and I just don't know about it?
I did notice some updates already with Rails 2.3.5.
1. _destroy has been changed to _delete
2. a[:content] is not recognizing the string representation of content, so it must be a['content']
I am loving the new changes and can't wait till Part 2!
Ryan, when you work on the second part of this tutorial, add a belongs_to relationship to Survey. For example: author. In survey.rb add accepts_nested_attributes_for :author. Incorporate this into your form.
I mention this because nested forms doesn't handle belongs_to relationships properly. If you want to change the author for a single survey, it will do something like:
update authors set name = 'bar' where id = 1
Which affects all surveys that point to that author.
What it should do is:
insert into authors (id, name) values (2, 'bar')
update surveys set author_id = 2 where id = 5
Thank you very much for your work.
Is there a way to integrate accepts_nested_attributes_for and formtastic?
looing forward to see your part two
I asked the same question Yinghai, someone claimed you could, but I've not yet see it work.
Ryan, I'm with Lyle. Is there any way you can get this on the opposite end of the relationship on the belongs_to? It should work is what I've seen on the internet but I keep getting errors.
Also, does it work with anything other than a has_many with belongs_to relationship?
@branden, did you get an answer for this? I want to use has_one and belongs_to relationship for question-answer. and it is not working
_delete vs _destroy:
DEPRECATION WARNING: _delete is deprecated in nested attributes. Use _destroy instead.. (called from _delete at /usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/nested_attributes.rb:263)
Thanks!
StuFF mc, Ryan is using the Textmate "Ruby on Rails" bundle to create the partials. This is available with "control shift H" or from the bundle menu "Ruby on Rails > View Templates > Create partial from selection"
David, Ryan is using Textmate's column edit to quickly change the "builder." to "f." To use this push and hold the option button, your Textmate cursor changes to a cross, left click and drag the cross to select the column of text you want to change. Once you have a selection just type the new text you want.
Nice work Ryan - Thanks for picking up complex forms again.
Btw. is there a simple way to associate already created questions with a new survey?
Can a survey contain questions that are already part of other surveys?
Thanks
yanosz
@steve I had the same issue. I think Ryan's setup must have magic in it cause the api says to do it the way you did and not with :symbol.
Another great screencast and glad you're updating your Complex Forms series. That's been one of my favorites, but
@ryan, or anyone for that matter, do you think you'll ever address how to get the same model multiple times in the one form?
Great screen cast, just what I need right now!
I'm trying to understand the :reject_if => lambda { |a| a[:content].blank? }
I have forms with multiple inputs and checking for blank inputs wants all of them filled out. For example, if instead of "Question" as the input it had "First Name", "Middle Name" and "Last Name". How can you check that the first name is not blank but have it be optional whether to fill out the middle name? Which levels of the nesting attributes have to have no blanks to validate?
Thanks!
I didn't read all of the comments but I just ran into something on rails 2.3.2, when I use the
:reject_if => lambda{|a| a[:content].blank? }
it was rejecting everything, I needed to change it to
:reject_if => lambda{|a| a['content'].blank? }
Not sure if it was something silly I was doing or not but worth mentioning if it saves someone some time.
Looking forward to Parts 2 and 3!
As always, thanks for the great cast.
I was wondering if there was a way to access the underlying model from within a form builder, to use data from the db to dynamically create things like the "labels" for the form.
So let's say you have the following form: http://pastie.org/780413
Is there some way that I can get data from the db for instance for the label. So that in stead of "Question", I can do something like question(:name) or question.name or question[name] or whatever it would be. I've tried a lot of different things.
I'd be using it in a different context, so that would explain why it may not make much sense in the current example.
I'd appreciate any help.
-A.
Does anyone know how can we use this method with Paperclip plugin?
I mean, when we have Survey model and Photo model for example.
Every Survey has many Photos, i.e. Survey has multiple attachments.
Thanks in advance!
@Sergei
Look into polymorphic Paperclip attachments :)!
Sorry I can't get to everyone's question, but for those having trouble with the "a[:content.blank?" and "_destroy" behavior working, make sure you're using the latest version of Rails (2.3.5). This behavior has changed recently, and even some of the documentation is out of date.
I have rails 3.0.3 and it seems impossible to make content.blank? work with both create a destroy. And i should add my nested element use paperclip.
Ryan - you are my savior -
needed a solution like this for some time now. But i still have a question
How can i build a survey with many questions and many answers but all user see the same questions and can have only one answer per question. Only the admin can see and edit multiple answers and questions. Your help is very much appreciated
What if I need in partial views/surveys/_answer_fields.html.erb access to some answer attribute, for example answer.id, just use there f.object.id ? Not very nice solution, anyone has better one ?
Thanks, DanS! I love it! I never even knew to try that! (Re: TextMate's column edit)
I'm implementing the Remove checkbox option. When the user checks the first of the nested records for removal and I perform a page.reload, the line is removed; however, the first checkbox of the remaining lines is checked. This only occurs in Firefox. It's fine in Safari and Chrome. Does anyone have any ideas on how to fix this problem?
can anybody help me. i always get
unknown attribute: _destroy when trying to delete a record.
Hi Ryan
Thanks for this screencast. I am pointing out another general issue here. I am validating html at
http://validator.w3.org/check
I just added validates_presence_of :name in survey model and without a name when i submit as usual i get the page with error list And when I validates its source I got some error That is exactly as
document type does not allow element "div" here; missing one of "object", "ins", "del", "map", "button" start-tag
<div class="fieldWithErrors"><label for="survey_name">Name</label></div><b.....
Why this happens?Is it any issue?
Thanks again
sijo
I can only get this to work with projects *created* using the latest version of Rails. The questions are never inserted into the database. It doesn't seem to matter that I have upgraded Rails. Does anyone know what I need to change in a project created with an older version to get this to work?
What if you always want to start with at least one question? Let's say a user submits a survey with no questions, but then wants to add a question when editing the survey?
I know this can be done via javascript (see part 2), but how would I do this without javascript?
I'm basically looking to get the edit view to populate with at least one question field even if that question doesn't exist, and when update_attributes is called to add the new question that was entered.
At the moment, I can do:
If @survey.questions.empty?
@survey.questions.build
end
In my edit method, but the update method is not saving the new question added when editing a survey.
Help!
Thanks for the screencast Ryan :-). I also have validations set up, however, on error the child model errors are displayed first, instead of the parent's. Since the parent fields are the first to show up, those errors should be displayed first. any ideas on what I could be doing wrong? Thanks again.
Very Good!
I am work in Windows + Rails 2.3.4,have some problems.
a. proc {|a| ..} replace lambda {|a|..}
b. <%= f.check_box :_delete %> replace <%= f.check_box :_destroy %>
this is an awesome tutorial. But when i try it out, i encounter some problem.
It simply won't save the questions and survey name to the database after i added field_for in my view. Anyone else having that issue?
If I remove it, survey name are saved
This is going to sound kind of dumb--I'm sure I just have a missing bracket or something--but when I follow along, I can't get anything at all to render after the fields_for call.
In the following example code, TEST 1 shows up, but TEST 2 and TEST 3 do not--and neither does the partial. The next thing is the submit button.
I would appreciate any help!
Here is my code:
<p>
<%= f.label :birthdate %><br />
<%= f.date_select :birthdate %>
</p>
<p>
TEST 1
<% f.fields_for :roles do |builder| %>
TEST 2
<%= render "_role_fields", :f => builder %>
TEST 3
<% end %>
</p>
<p><%= f.submit 'Create Actor' %></p>
<% end %>
Okay, I figured it out, but it doesn't make any sense to me.
In my code, an actor has many roles, so I wrote <%= f.fields_for :roles do |builder| %> and that didn't work.
Changing it to <%= f.fields_for :role %> works. Maybe this is because at the beginning a New Actor has no roles? Is 0 singular?
It works, so I guess I don't care, but I'd sure like to know why, if anyone gets a minute. Thanks.
Yep. When I added the pre-building 3 roles to my New action, :roles worked. Sorry, I'm a newb! Thanks for the Railscasts, Ryan--they're a great tool.
Thank you, Nicolás Hock!
In Rails 2.3.4
builder.check_box :_destroy
should be
builder.check_box :_delete
This is a great screen-cast, but how do you display a nested attribute in the index view.
I keep getting nil?
error.
Hey Ryan, Thanks for the tutorial. It would be awesome if i can get it so work tho... Whenever i type questions for a new survey and hit 'submit' the questions never get to the database.. . I'm running rails 2.3.5 on windows xp64 and Ruby 1.8.7.
The surveys are getting through just not the questions.
Any ideas on why that might be?
Hi, was just going thru this tutorial. All is fine but when I try to render the nested forms for the questions or answers in the main form, I get an error saying unable to find template /surveys/_questions_form.rb
Logs dont tell much except it points to the line which is calling the render.
I am not sure of the resource.map and how it works but is there something else I need to do to render correctly?
I am running Rails 2.3.5
Does someone knows how to implement FCKeditor on a nested attribute?
Hey Ryan, great screencast! Didn't know it existed until just now :)
In the beginning of the screencast you say there isn't much documentation on creating the views, but there is in fact some in the fields_for docs: http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#M001605
You might want to add that link to the list of links.
Cheers
Is this broken in Rails 3 for anyone?
Hay @Shai, I was following this tutorial in Rails 3 and it is broken indeed. I get a ActiveRecord::AssociationTypeMismatch with the message
User(#11741180) expected, got ActiveSupport::HashWithIndifferentAccess(#3929460)
Very dissapointing. I may be doing something wrong, but I have checked this from every possible angle and I guess it's Rails 3 fault. Actually, I removed the accepts_nested_attributes_for call from the model and submitted the form and I got exactly the same error.
Sorry, I posted my website url wrongly in the previous comment.
And to add something to the previous comment (and not being suspected as spammer) I may add that the only thing that's left for me to confirm this, is to test my code in Rails 2.3.x, but unfortunately the project I'm working on is already being mounted on Rails 3 and already absolutely dependant on it. I may extract the relevant parts and test it on Rails 2.3.x to see if it works.
I ran this episode's project both on rails 2.3.5 and rails 3.0.0.beta3 and it works great, so I guess it's me. I'm shocked :-O
newbie question: why ryan uses survey_id:integer and question_id:integer when generating models and not survey:references and question:references. what is the difference? thanks
Ryan, excellent Railscast thank you.
How are you populating the form with sample questions simply using a keyboard shortcut?
I noticed a lot of people running into a problem where their nested records were not saving to the data base.
There seems to be an issue with what Rails version is being used. But if you are using 2.3.5 or higher your code should work just as Ryan says.
I made a stupid mistake that had me stumped for hours, so I thought I would make a note of it in case anyone else is having the same problem.
The mistake I made was a typo in the accepts_nested_attributes_for in my model. You should double check the symbol that you are checking if '.blank?' or not.
If you have a typo, then of course it will be 'blank?' and therefore will always be rejected and never saved.
Example below of typo:
accepts_nested_attributes_for :links,
:reject_if => lambda { |a| a[:typo].blank? },
:allow_destroy => true
I wish you would do a screencast about how to add multiple records of a single model with one form. I've done a ton of searching and can't seem to find a satisfactory answer that doesn't involve using a parent class.
Suppose you have to assign a "correct" answer through a radio box beside each answer string.
For instance (_answer_fiels.html.erb):
<%= f_question.radio_button :answer_id, f.options[:child_index], :checked => false %>
<%= f.text_field :content %>
--
I can't get the id of the new answer ! Can anyone help me???
Your railscasts are great !
I still have a problem :
parent model, child model
How can I set automatically some values in child fields il
parent and child objects are new ?
@niber: same question.. I was trying f.options[:child_index]
Is there any way to define a callback method when for instance each answer is saved?
HI,
I need to know if any nested attributes is blank then how it would work?
e.g -
In my case user have addresses & photos(nested attributes) but not mandatory while adding user if i haven't added photos & submit form then while editing that user it will not shown me photo upload field because photo object is not exist for that user
can you explain me how should it work?
did you get this to work? and how?
I am using Rails 4
So, this may not be the issue, and I'm too late to help either of you, but in case someone else is looking for this: In Rails 4, you need to use <%= f.fields_for..., not
<% f.fields_for... Note the = after <%.
For those of you having validation errors due to the child being saved before the parent, this has been fixed in Rails 2.3.6 with the :inverse_of option.
See these links:
https://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/2815-nested-models-build-should-directly-assign-the-parent
and
http://github.com/oggy/inverse_of
@Sanjee I think he's just editing the part he enters it normally via keyboard. Saves us the trouble.
Very successful in both content and style sheets. Thanks webmaster and content editor
asd
Caveat using Rails 3.0.1 and Nifty Generators 0.4.2:
Nifty Generators will generate:
attr_accessible :name # which is not compatible with accepts_nested_attributes_for "this way" e.g. it (correctly) prevents nested attributes to be saved.
Maybe this should be added to a Rails3 update notice ;-)
King regards
ionas
In Rails 3.0.1 it seems that once a question is created it does not get removed if its blank. E.g. the way Ryan shows it does not work but when creating a new Survey blank questions do not get saved (correct way).
In rails 3 you should use :
<%= f.fields_form [...]
instead of :
<% f.fields_form
same goes with form_for
Thanks! In Rails 4 it's the same.
How would I assign the user_id to current_user.id for the nested model?
I have an Item class that has many datafiles (paperclip attachment model). I tried:
def create
@item = Item.create(params[:item])
@item.datafiles.build( :user_id => current_user.id)
end
The line @datafile.user_id=current_user.id in the datafiles controller works fine if I create a datafile in the datafile form but not when created in a nested item form.
Cheers J.
Thank you again for this railscast ;)
I have one doubt about the Question.rb example. If I use validates_presence_of :answers, and I send the form with _destroy = true, the nested model is destroyed without the validation
How can I fix this validation problem?
class Question < ActiveRecord::Base
belongs_to :survey
validates_presence_of :answers
has_many :answers, :dependent => :destroy
accepts_nested_attributes_for :answers, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true
end
Hi everyone,
First of all congrats for this great community and work is really satisfactory see so much help.
Second, I have read that if you have included accessor methods to your fields (attr_accessible and/or attr_protected) you have to define the attr_writer, is there any example with this due to I'm not understanding how to implementing it.
Kind regards.
Hi,
In Rails 3, if you are failing validations due to validating the parent_id in the child model when parent.new_record? and therefore parent is not yet saved, here's a solution.
http://stackoverflow.com/questions/2102724/rails-nested-attributes-association-validation-failing
Hi everyone wonderful episode,
but a small problem i'm facing that is
i have a has_many association set up between category and sub category,
Class Category ..
attr_accessible :name, :subcategories_atttributes
has_many subcategories, dependent => :destroy
accepts_nested_attributes_for :subcategories
end
Class Subcategory..
belongs_to :category
end
error which i get while saving a category along with its subcategories is
* Subcategories category can't be blank
thanks in advance
Hice! Thx, but I have error "NoMethodError in ClientsController#update undefined method `eq' for nil:NilClass"
def update
@client = Client.find(params[:id])
respond_to do |format|
if @client.update_attributes(params[:client])
format.html { redirect_to(@client, :notice => 'Client was successfully updated.') }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @client.errors, :status => :unprocessable_entity }
end
end
end
Here's an update:
Is there a way to update a nested form in a partial from the controller with an update page do call?
I build the Keyword form in a partial
Now I call a controller action from an observefield tag.
n.times { campaign.keywords.build}
page.replace_html "form keyword", :partial => "keyword"
If I place the entre form in a partial, the call goes through, however, If I only have the keyword-part in the partial I can
Hi, I have been trying to create a multistep Form (referencing episode #217) and my form has nested attributes as in episode #196.
I have merged the idea from both of these episodes.And I am in problem.
I have two Models.
Models
1) Event has_many: invitations
accepts_nested_attributes_for : invitation,:dependent=>:destroy
2) Invitation belongs_to: event
Controller --Event
View:Event(new)
MY PROBLEM :: WHEN I GO TO next_step...the view nor show the nested_field atrributes NOR it shows any error..it simply skips the entire nested form fields....i'm going nuts...how can it simply skip the code!! any idea!!
If somebody gets stuck on the part when form doesn't generate nested fields
<% f.fields_for :questions do |builder| %>
then in Rails 3.1 you have to change the tags to
<%= %>
I've wasted hours on that...
Thanks man! you saved me hours of searching....
Thanks Jakub, i was stuck and you came through for me.
Excellent tutorial! And a huge thank you to Jakub for the Rails 3.1 help!
Ctrl-f, rails 3.1... and I find my savior Jakub!
It's January 2012 and this comment still delivers.
Thank you, Jakub!!!
I suppose I should have checked that first, but again thank you very much. Was very frustrated.
thanks a lot for this, was pulling out my hair over it!
Thank you Jakub! I was struggling debugging, hard to spot.
Jakub have my babies!
You didn't waste any hour. You sacrificed those hours for the betterment of humanity.
I cannot seem to get this to work as I would want, and I don't see how to change it... from the examples given, it only allows for 1 question/answer.etc. because the html looks like this:
when it should be like:
in order to get an array in the params when it reaches the server... anyone got a solution for this?
What is the HTML supposed to look like again?
Hi! Please help!
I am stuck on this error:
ActiveRecord::UnknownAttributeError in SurveysController#new
unknown attribute: survey_id
Rails 3.2.2
I have the same problem, did you solve it?
no :(
my mistake was that I did not add 'survey_id:integer' while generating questions model. it solved the problem
I am having the same problem...tried all say...but no solution..plz post a solution if you come to know
Very nice tutorial. Thanks a lot.
At Rails 3.2.*,
I replace,
nifty_layout
->nifty:layout
nifty_scaffold
->nifty:scaffold
and concate nifty gem entry on Gemfile
also add line in
app/models/survey.rb
fileWas having problems Updating the widgets when saving a lecture through update_attributes(...). It was a matter of accessibility of the attributtes of widget.
The last line of the widget class made all the difference.
in ASCII-Cast, the view of the form should be
you forgot the = (equal sign), so the questions would not appear ;-)
keep on casting, very good work ryan
marcello - railszilla.com
Thanks for this! I was about to go search the Interwebz...Great screencast, Ryan!
Hi Ryan
Maybe some one have tell you but if not I will.
I suppose is a little typo or error.
If you and see in your screencast at 04:30, you will watch this line:
There is an error on
<%
, you must use<%=
. It's a little issue but it could make you to spend a lot of time trying to solving it.Greetings from Mexico
Thanks Israel :)
You are welcome :)
Yep! Thanks!!! =)
I'm not sure if it's exactly the same thing, but what really saved me (for what I needed) was this https://github.com/moo-li/Simple-parent-child-forms-in-Rails-3.1
Great railcast anyways!
Ryan -
Love your screencasts but just a tip. Im a newbie and it seems like almost every screencast leaves out one or two small little details that are taken for granted. For example, I tried to setup a nested form here following your tutorial exactly and I couldn't get the nested fields to show up. After much research I learned that I needed to build the nested attribute within the parent's controller NEW action. Once I did this, the fields showed up. You do not show this anywhere on your notes or anything and I think steps like these are taken for granted. My recommendation is that your show notes should be completely thorough and should be a complete working representation of the code to make it work. You go through the process of starting a new app in this video (which I think could be taken for granted), but you leave this part out (which should not). Anyways, thought this would help...
Sorry guys but how can I reorganize the fields?
<%= f.fields_for :answers do |builder| %>
That's because I've already done a Drand and Drop ajax order script and now I need to know how to order the fields.
Thanks.
in our scenario we need to vary the number of associated records allowed. We have validation in the model i.e
accepts_nested_attributes_for :answers , :limit => 4,:allow_destroy => true
My question is . how do we prevent the Add Answers link from being rendered if we already have reached our limit ?
@chris, I am trying to limit the answer to one, did you find a way to prevent the Add Answers link from being rendered if we already have reached our limit?
Hi Ryan --
I was working out a different problem and wanted to get to a known starting point, so ended up at this episode, which you have since revised. The code here doesn't work in a default Rails 3.2 environment for a couple of reasons which are resolved in the revised version.
I wonder if you might want to add a feature to your site, that provides a notification when an episode has been revised with a link to the new one? Or perhaps if you haven't yet revised an episode just a note. For example, before the revision, this one might have a note like "As of Rails 3.2 the code in this example does not work. See comments for solutions."
I have been using Rails since 2007, and it's a testament to your understanding of how all of us actually learn to code that you have picked topics that live for years!
You rock!
Tom
All those who come later:
When you're auto generating your 3 questions be sure to make the fields_for line visible using <%= instead of just <% otherwise you won't see the 3 questions.
I'm using Rails 3.2 in case it matters.
Good hunting,
Mike
Thanks Michael Hawkins. That comment put an end to my misery.
Indeed! Thanks for posting about the update.
I've just spend about an hour to find that out - finally, thanks to your hint, I did^^
Rails 4 docs give slightly different syntax:
FYI - To get this to work in Rails 4 (I just generated the questions for my example so you will need to add for answers), you need to add to the bottom of the Survey Controller:
def survey_params
params.require(:survey).permit(:name, questions_attributes: [:id, :content])
end
Would I need to add the params for the answer to the survey class or to the questions class?
I got stuck on the params.require/permit (Rails 4.2.4).
Note: my models have different fields than in the video example, but the nested permit structure for attributes should help you out. Notice how the answers_attributes is located inside the questions_attributes .
This is what wound up working for me
Also in Rails 4, remember to add the _destroy method to permitted params. Like this:
you also need to add it in the QuestionsController
Brunzino, did you make it with rails 4.. could you please send me the code! It will be really appreciated
please can some one help me with this problem here? I am using rails 4. http://stackoverflow.com/questions/21295989/nested-attributesmodels-forms-not-working-as-needed-in-rails-4
I want to use a has_one relationship for questions-answer.
Thanks
pls how do i use this to create a profile for my users....email me @ dehinde007@gmail.com
Hello Guys I have just completed this tutorial in Ruby 2 and Rails 4, If anyone needs help email me at
steve.pdp@gmail.com
Hello Ryan, thanks for your excellent guide.
I had a column like reference_id in answers model. I want to make it unique through entire Survey.
answers model
validates :reference_id, uniqueness: { scope: :question_id }
It is applying only for questions but what to do if i want apply through the survey ?
First Off this this a very good tutorial. But i am having some Issues with the select fields and they are not being populated correctly on the nested fields
One of my nested Form Fields:
If i do this i get the year correctly and populated
<%= f.text_field :year %>
But what do i pass in this select field to populate the correct year.
I know it will be a second input in the option_for_select but how to i get the object that is being inputed
f.year Does Not Work..
<%= f.select :year, options_for_select((1900..Date.today.year+1).to_a.reverse), {:prompt => 'Year', :class=>"pointer" } %>
How to pass locales for question_fields partial. Can anyone help me out.
<%= f.fields_for :questions do |builder| %>
<%= render "question_fields", :f => builder %>
<% end %>
I have tried the following way and tried to access type in question_fields. It's thrown error(Undefined variable type)
<%= f.fields_for :questions do |builder| %>
<%= render "question_fields", :f => builder, :type => "Test" %>
<% end %>
This episode has been updated to Rails 5 as a blog post Complex Forms in Rails 5.
I use a different approach:
This way I don't need any helper_method.
Just a correction in order to rewrite the ID as well:
You've done a very good job.
Amazing stuff.