【发布时间】:2019-01-05 21:01:23
【问题描述】:
我创建了一个 simple_form_For 通用的 new 和 update, 目前,它对 new 工作正常,但对于编辑/更新,它调用了错误的 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 中
<%= simple_form_for @post, url: newsfeeds_path(@post) do |f| %>
<%= f.input :content,label: false, placeholder: "write your post here..." %>
<%= f.button :submit %>
<% end %>
在浏览器上的检查元素上, 我做错了,
必须是 action="/newsfeeds/7"
请指导
【问题讨论】:
-
你对这两个动作使用相同的形式吗?不遵循 Rails 约定并将请求发送到 NewsfeedsController 而不是 PostsController 的原因是什么?
-
我已经告诉过不要遵循 Rails 约定,这就是它使 form_for 变得复杂的原因。我没有任何后期控制器。
-
这里@post 会自动获取id,否则我们必须使用“@post.id”
-
如果你真的想强制违反 Rails 约定(有点愚蠢的建议——尤其是当当前没有 PostsController 时),那么你必须确保表单使用不同的 URL 来创建和更新方法。先是
POST newsfeeds_url,后是PATCH newsfeed_url(@post)。
标签: ruby-on-rails ruby updates edit simple-form