Simple_form_for操作在Rails中的编辑上输入了错误的URL [英] Simple_form_for action hitting wrong URL on edit in rails

查看:92
本文介绍了Simple_form_for操作在Rails中的编辑上输入了错误的URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经为new和update创建了simple_form_For公用,当前,它可以很好地用于新的,但是对于编辑/更新,它调用了错误的URL.

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

在Form.html

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 %>

在浏览器上的inspect元素上,我做错了动作,

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

它必须是action ="/newsfeeds/7"

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

请指导

推荐答案

当您使用通用的_form进行更新和更新时,需要分别在url中添加条件,

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| %>

这将帮助您同时使用new和update方法.希望这会有所帮助.

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

这篇关于Simple_form_for操作在Rails中的编辑上输入了错误的URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆