Question

I have two models: User and Description. All User's have one Description and all Descriptions belong to a User. I created a form that creates a description, but when I tried to retrieve description data in a view, I couldn't. I checked my database and the user_id column of the descriptions table is not updating. I thought this should happen automatically with a has_one/belongs_to relationship. How do I fix this so that the user_id field automatically gets filled with the user's id?

Here's my user model:

class User < ActiveRecord::Base
   has_one :description
   accepts_nested_attributes_for :description
end

Here's my description model::

class Description < ActiveRecord::Base
    belongs_to :user
end

Here's my description controller:

class DescriptionsController < ApplicationController

        def new
            @description = Description.new
            @current = current_user.id
        end
        def create
            #Description.create(description_params)
            @description = Description.create(description_params)
            redirect_to student_path
        end
        def index
        end

    private

    def description_params
      params.require(:description).permit(:skills, :looking_for, :my_idea, :user_id)
    end
end

And here is the view:

<div class="span6 offset3 text-center">
<h1>Edit your information</h1>

    <%= simple_form_for @description do |f| %>
        <%= f.input :skills %>
        <%= f.input :looking_for, :label => 'What help do you need?' %>
        <%= f.input :my_idea %>
        <%= f.input :user_id, :as => :hidden, :value => @current %>
        <%= f.submit "Save", :class => "btn btn-primary btn-large" %>
    <% end %>
</div>

I've tried removing user_id from accepted params - that does nothing. I've also tried passing the user_id in using a hidden field - this did not work, but I also don't think it should be necesarry and i don't think it would be the right way to fix the problem.

Was it helpful?

Solution

If you're using accepts_nested_attributes_for, the idea is that you'd submit the attributes for the Description model as part of the form for your User model. That doesn't appears to be what you're doing here.

If you don't want to do that, you should remove that line and in your controller do

current_user.build_description(description_params)

(or you can use #create_description if you want to initialize/save all at once).

For example

def create
  @description = current_user.create_description(description_params)
  redirect_to student_path
end

See the Active Record Associations guide for documentation for these has_one methods.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top