My user model has_many Answers. I am trying to create a nested form to create a new user with three child answers. My code looks the same as Rails, but although it saves the user, it will not save the answers. Can anyone understand what is wrong?
users_controller.rb
class UsersController < ApplicationController def new @user = User.new 3.times{@user.responses.build} @responses = @user.responses end def create @user = User.new(user_params) if @user.save redirect_to @user
user.rb
class User < ActiveRecord::Base attr_accessor :responses_attributes has_many :responses, :dependent => :destroy accepts_nested_attributes_for :responses#, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true before_save { self.email = email.downcase } validates :username, length: { maximum: 50 } VALID_EMAIL_REGEX = /\A[\w+\-.] +@ [az\d\-.]+\.[az]+\z/i validates :email, presence: true, format: { with: VALID_EMAIL_REGEX } , uniqueness: {case_sensitive: false}; validates :responses, presence: true end
response.rb
class Response < ActiveRecord::Base belongs_to :user validates_presence_of :user_id, :content end
users / new.html.erb (form)
<h1>This is a test form for adding Users with child Responses</h1> <%= form_for @user do |f| %> <%= render 'shared/error_messages' %> <%= f.label :username %> <%= f.text_field :username %> <%= f.label :email %> <%= f.text_field :email %> <p> <%= f.fields_for :responses do |builder| %> <%= builder.label :content, "Response" %> <%= builder.text_field :content %> <% end %> </p> <%= f.submit "Submit" %> <% end %>
Edit:
I changed the strong settings in the Users controller to:
def user_params params.require(:user).permit(:username, :email, responses_attributes: [:content]) end
And I updated the User model to:
class User < ActiveRecord::Base has_many :responses, :dependent => :destroy accepts_nested_attributes_for :responses#, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true before_save { self.email = email.downcase } validates :username, presence: true, length: { maximum: 50 } VALID_EMAIL_REGEX = /\A[\w+\-.] +@ [az\d\-.]+\.[az]+\z/i validates :email, presence: true, format: { with: VALID_EMAIL_REGEX } , uniqueness: {case_sensitive: false}; validates_associated :responses, presence: true end
Now it continues to fail in my responses to the responses, and also fails to complete my checks for username and email.