Search code examples
ruby-on-rails-4nested-resourceshas-one

Rails 4 build_association


in my rails 4 app, i have a user model that has_one profile model which also belongs_to the user model

this is my first time using a nested resource so im kinda lost to it here how it goes , a user creates an account,after succesful email authentication , user proceed to create a profile. Problem is, im getting error on using the build_association. Im not sure whether the problem is actually that or im getting null values on the params(which i think not)

in my routes.rb

resources :users do
   resources :profiles
end

profiles view, new.html.erb

<%= form_for(@profile,url:{ :controller => 'profiles', :action => 'create'},html: {class: "ui large segment form error"})  do |f| %>
    <%= render 'shared/form_error_messages', object: f.object%>
        <div class="ui horizontal divider">Create a Profile</div>
            <%= f.text_field :first_name, :placeholder => "First Name" , :required => true%>
<%= f.submit "Submit Profile", class: "ui submit button"%>
    <% end %>

profiles_controller.rb

def new
    @user = User.find(params[:user_id])
    @profile = @user.build_profile
end

def create
    @profile = @user.build_profile(profile_params)
    if @profile.save
        flash[:success] = "Profile has been created"
        redirect_to root_url
    else
        render 'new'
    end
end 

private
def profile_params
    params.require(:profile).permit(:first_name)
end

when im submitting the form, im getting

NoMethodError in ProfilesController#create
undefined method `build_profile' for nil:NilClass

Application Trace | Framework Trace | Full Trace
app/controllers/profiles_controller.rb:9:in `create'
Request
Parameters:
{"utf8"=>"✓",
"authenticity_token"=>"MFCANYra..",
"profile"=>{"first_name"=>"sample",
"commit"=>"Submit Profile",
"user_id"=>"1"}

Solution

  • Try changing the create action in profiles_controller.rb as below :-

    def create
      @user = User.find(params[:profile][:user_id])
      @profile = @user.build_profile(profile_params)
      if @profile.save
          flash[:success] = "Profile has been created"
          redirect_to root_url
      else
          render 'new'
      end
    end 
    

    let me know this worked or not, try to find if something else is causing the problem, thanks.