This is my first question on SO. W00t!
As in this railscast, I’m able to create a survey model and form which accepts accepts_nested_attributes_for questions, and the questions model accepts_nested_attributes_for answers.
If users are signed in, then I can associate their answers with their user_id. However, I’d like to make it possible for guests to fill out this form too. This would be a great way to lower the barrier to participation.
I’d like guest users to be able to add their name to the form so other users can distinguish between guests that have not yet created accounts. To do that, I’ve created a guest_name field in the answer model.
The problem: If they add their name to the form after they create new answers, how can I associate their name with their answer?
Inside surveys_controller.rb I am currently creating a variable called @responding_user_id and setting it to the signed-in user’s ID or setting it to 0 if no one is signed in:
@responding_user_id = (current_user ? current_user.id : 0)
so that inside answer.html.erb, I can do this to associate the signed-in user’s ID with his/her answer:
<%= f.hidden_field :user_id, :value => @responding_user_id %>
In the survey, users see multiple questions and they can add one or more answers to any question by clicking the “Add Answer” link from the partial called _question_fields.html.erb:
<%= f.fields_for :answers do |builder| %>
<%= render 'answer_fields', f: builder %>
<% end %>
<%= link_to_add_fields "Add a New Response", f, :answers %>
I guess I could force them to input their name prior to adding answers and then change the hidden user_id fields through jQuery, but that is not an optimal user experience.
The only part of this that I’m having trouble with is assigning the guest name to the answer’s hidden user_id field. The reason this is difficult is that the HTML for the hidden field is generated when the user clicks “Add Answer” and at that point, they may not have entered their guest name yet.
Maybe the only way to do this is with jQuery as mentioned above?
Thanks!!
First of all, here do you suppose to store the guest’s names? You have just a
user_idfield. so you have to change your model.