user7391609
user7391609

Reputation: 21

Rails undefined method * for nil:NilClass

I am having an issue and I have done some reasearch, from my research I have found that the variable that is being used is empty, however I am unsure as to why it is empty, Maybe its something obvious to someone else?

I am trying to display a nested form on a page from another controller, I am used nested resources, Which I think might be my issue, but unsure how to resolve it.

Getting the following error:

undefined method `submission' for nil:NilClass

Structure of Project Main Folders -Members --Questions --Submissions

Concept:

Question - has_many - Submissions Submission - Belongs_to - Question

Submission Model:

class Submission < ActiveRecord::Base
    belongs_to :question
    belongs_to :member
end

Question Model:

class Members::Question < ActiveRecord::Base
  has_many :submissions
end

Submissions Controller:

def create

        @question =  Members::Question.find(params[:question_id])
        @submission.member_id =  current_member.id
        @submission = @question.submissions.create(params[:submission].permit(:content, :question_id))

*Redirect Method Here * 

end

In the form I am using the following method:

<%= form_for([@question, @question.submission.build]) do |f| %>
  <% if @submission.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@submission.errors.count, "error") %> prohibited this submission from being saved:</h2>

      <ul>
      <% @submission.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :content %><br>
    <%= f.text_area :content %>
  </div>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

And then to display the form on the show page of the question, I am using

<%= render 'members/submissions/form' %>

Routes:

  namespace :members do
    resources :questions,  only: [:index,:show] do
      resources :submissions 
    end
  end

Any one any ideas where I am going wrong?

Any help is appreciated.

Upvotes: 0

Views: 9741

Answers (1)

user7391609
user7391609

Reputation: 21

I have solved the problem, Thank you for the suggestions, I was using the wrong variable, I was using @question, When because its nested, the correct variable is @members_question

Submissions Controller

def create

        @members_question =  Members::Question.find(params[:question_id])
        @submission = @members_question.submissions.create(params[:submission].permit(:content, :question_id))
    @submission.member_id =  current_member.id

end

_form.html.erb

<%= form_for([@members_question, @members_question.submissions.build]) do |f| %>

  <div class="field">
    <%= f.label :content %><br>
    <%= f.text_area :content %>
  </div>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

Upvotes: 1

Related Questions