Search code examples
ruby-on-railsrubyupdateseditsimple-form

Simple_form_for action hitting wrong URL on edit in rails


I have created a simple_form_For common for both new and update, currently, it's working fine for new but for edit/update, it calling the wrong URL.

class NewsfeedsController < ApplicationController

    before_action :find_post, only: [:show, :destroy, :edit, :update]

    def index
        @posts = Post.all.order("created_at DESC")
    end

    def show
        # before_action is taking care of all 4 i.e(sho,edit,update and destroy)..Keeping it DRY
    end

    def new
        @post = Post.new
    end

    def create
        @post = Post.new(post_params)

        if @post.save
            redirect_to root_path
        else
            render 'new'
        end
    end

    def edit
    end

    def update
        if @post.update(post_params)
            redirect_to newsfeed_path(@post)
        else
            render 'edit'
        end
    end

    def destroy
    end

    private

    def post_params
        params.require(:post).permit(:content)
    end

    def find_post
        @post = Post.find(params[:id])

    end

end

In Form.html

<%= simple_form_for @post, url: newsfeeds_path(@post) do |f| %>
  <%= f.input :content,label: false, placeholder: "write your post here..." %>
  <%= f.button :submit %>
<% end %>

on inspect element on browser, i am getting action wrong,

it needs to be action="/newsfeeds/7"

Please guide


Solution

  • As you are using common _form for new and update, you need to add condition in url respectively,

    <%= simple_form_for @post, url:(@post.new_record? ? newsfeeds_path : newsfeed_path(@post)) do |f| %>
    

    This will help you using both new and update method. Hope this will help.