Search code examples
ruby-on-railsupdatesscaffolding

Weird redirection when updating datas


I generated a scaffold for a portfolio via the Rails command, rails g portfolio titre:string, thumbnail:string lien:string description:text. I also added FriendlyId to get a better URL, and that's about all. Here is the 'update' action.

  def update
    if @portfolio.update(portfolio_params)
      redirect_to @portfolio, notice: 'Portfolio mis à jour.'
    else
      render :edit
    end
  end

However, when trying to update a project in my portfolio, the submit button tries to get to 'portfolio#update' via patch, but puts a '.' instead of a '/' which gives me No route matches [PATCH] "/portfolios.test-1"

For the route, I only have resources :portfolios

edit : added the form

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

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

  <div class="field">
    <%= f.label :titre %>
    <%= f.text_field :titre %>
  </div>

  <div class="field">
    <%= f.label :categorie %>
    <%= f.text_field :categorie %>
  </div>

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

  <div class="field">
    <%= f.label :thumbnail %>
    <%= f.file_field :thumbnail %>
  </div>

  <div class="field">
    <%= f.label :lien %>
    <%= f.text_field :lien %>
  </div>

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

I didn't have any other possibilities that doing @portfolio, url: portfolios_path(@portfolio), otherwise Rails considered that '@portfolio' was nil

edit 2 : added the private 'set_portfolio' params

private
  # Use callbacks to share common setup or constraints between actions.
  def set_portfolio
    @portfolio = Portfolio.friendly.find(params[:id])
  end

What's wrong with my app ?


Solution

  • portfolios_path is the collection path.

    change it portfolio_path should fix it.

    <%= form_for @portfolio, url: portfolio_path(@portfolio) do |f| %>

    I guess you are going to use this form for creating new portfolio as well, so change it to <%= form_for(@portfolio) %> should fix it and will also work for both cases. form_for will submit to correct path.