Simple_form_for action hitting wrong URL on edit in rails

泪湿孤枕 提交于 2021-01-29 07:18:39

问题


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


回答1:


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.




回答2:


Update action should be newsfeed_path(@post) and not newsfeeds_path(@post). Please correct it and try again!

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

Hope that helps!



来源:https://stackoverflow.com/questions/54051759/simple-form-for-action-hitting-wrong-url-on-edit-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!