K Waters
K Waters

Reputation: 63

undefined method '[]' for nil class rails

Why is this an undefined method? It says that the error is at this line:

  @member.room.update(rent: params[:member][:room_attributes][:rent], room_name: params[:member][:room_attributes][:room_name])

members_controller.rb

def edit
    @member = Member.find(params[:id])
end

def update
    @member = Member.find(params[:id])
    @member.room.update(rent: params[:member][:room_attributes][:rent], room_name: params[:member][:room_attributes][:room_name])
end


def member_params
    params.require(:member).permit(:name, :room_id,
                                    room_attributes: [:rent, :room_name, :member_id],
                                    purchase_attributes: [:description, :cost, :member_id])
end

edit.html.erb

<h3> Member Name </h3><br>
<%= @member.name %><br>
  <%= form_for @member.room, url: member_path(@member) do |f| %>
    <%= f.label :room_name %><br>
    <%= f.text_area :room_name %><br>
    <%= f.label :rent %><br>
    <%= f.text_area :rent %><br>


    <%= f.submit "Submit" %>

  <% end %>

Upvotes: 0

Views: 94

Answers (2)

ddavison
ddavison

Reputation: 29092

Since you are using Strong Parameters, Trying using:

@member.room.update(rent: member_params[:member][:room_attributes][:rent], room_name: member_params[:member][:room_attributes][:room_name])

(member_params instead of params)

Upvotes: 0

craig.kaminsky
craig.kaminsky

Reputation: 5598

The error indicates that one of your param keys is not set. When your form (in edit.html.erb) is output, what is the name and/or id of each form field.

By the looks of it, I seems like it would be room[room_name] when it would need to be member[room_attributes][room_name].

Upvotes: 1

Related Questions