Home > Back-end >  Rails doesn't send object as a param error
Rails doesn't send object as a param error

Time:09-27

I've got a controller that handles articles, and recently implemented the edit and create action that way:

def edit
      @article = Article.find(params[:id])
end

def update
      @article = Article.find(params[:id])

      if @article.update(article_params)
        redirect_to @article
      else
        render :edit, status: :unprocessable_entity
      end 
end

The error occours when I try to edit an article showing the message: screenshot

I'm using a form partial to load the layout this way:

<%= render "form", article: @article %>

After trying to save an new article the edit action works properly and the body error message doesn't shows if trying to save without the requirements. What should I do so solve this problem? Thanks in advance.

CodePudding user response:

There is a better way altogether to handle rendering errors - just access the object wrapped by the form builder:

<%= form_with(model: article) do |form| %>
  <% if form.object.errors.any? %>
    <ul>
      <% form.object.each do |error| %>
        <li><%= error.full_message %></li>
      <% end %>
    </ul>    
  <% end %>
  # ...
<% end %>

This lets you DRY out the rendering of errors messages without having to know the name of variable which corresponds to the model instance wrapped by the form.

However you also have a classic nil error - @article is most likely nil. And this isn't an issue we can actually help you with since it cannot be reproduced if we take the code in the question at face value. Like often with stackoverflow the actual problem it lurking somewhere outside of picture.

The debug this code you need to ensure that the code you think is running is actually running and set a series of breakpoints to verify that it is indeed being set and is being passed correctly all the way to the view.

CodePudding user response:

I see that you change article to @article in edit.html.erb. Because article does not exist. article exists when you render "form", article: @article use in _form.html.erb

  <% @article.erors.full_messages_for(:title).each do |message| 
    <div><%= message %></div>
  <% end %>

But i think you don't show errors in edit.html.erb

In edit.html.erb file

  <%= render "form", article: @article %>

In _form.html.erb

<%= form_with(model: article) do |form| %>
  <% if article.errors.any? %>
    <ul>
      <% article.errors.each do |error| %>
        <li><%= error.full_message %></li>
      <% end %>
    </ul>    
  <% end %>
  <div>
    <%= form.label :title, class: "form-control" %>
    <%= form.text_field :title %>
  </div>

  <div>
    <%= form.submit, class: "btn btn-primary" %>
  </div>
<% end %>

P/S: That's my opinion, if anyone has any ideas, please leave a comment. I thank you very much

  • Related