ruby on rails - Undefined method `answer' for class -


i have form can ask question , add question few answers.
when try save question , answers clicking 'create' error:

"undefined method `answer'" in questions_controller.rb in 'create' method. 

my question.rb model:

class question < activerecord::base   has_many :answers, :dependent => :destroy    accepts_nested_attributes_for :answers, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true    before_save { self.content = content.downcase }   validates :content, presence: true, length: { maximum: 150 } end 

my answer.rb model:

class answer < activerecord::base   belongs_to :question    validates :answer, presence: true, length: { maximum: 150 } end 

questions_controller.rb:

class questionscontroller < applicationcontroller   def show     @question = question.find(params[:id])   end    def new     @question = question.new     3.times       answer = @question.answers.build     end   end    def create     @question = question.new(question_params)     if @question.save       flash[:success] = "welcome sample app!"       redirect_to @question     else       render 'new'     end   end    private     def question_params       params.require(:question).permit(:content, answers_attributes: [:content])     end end 

and view new.html.erb:

<div class="row center-block">   <div class="col-md-2 col-md-offset-3">     <%= form_for @question |f| %>         <%= render 'shared/error_messages' %>          <%= f.label :content %>         <%= f.text_field :content %>          <%= f.fields_for :answers |builder| %>             <%= render "answer_fields", :f => builder %>         <% end %>          <div class="center hero-unit">             <%= f.submit "create poll", class: "btn btn-large btn-primary" %>         </div>     <% end %>   </div> </div> 

and rendered answer_fields:

<p>   <%= f.label :content %><br>   <%= f.text_area :content, :rows => 3 %><br>   <%= f.check_box :_destroy %>   <%= f.label :_destroy, "remove answer"%> </p> 

it's difficult track problem without stack trace, made me suspicious in form, have field content answer:

<%= f.text_area :content, :rows => 3 %> 

this processed in controller (again - you're allowing :content answers_attributes)

params.require(:question).permit(:content, answers_attributes: [:content]) 

but have validation in answer on field :answer:

validates :answer, presence: true, length: { maximum: 150 } 

try changing to

validates :content, presence: true, length: { maximum: 150 } 

hope helps!


Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -