我试着通读form_for Ruby文档,但仍然很难理解其中的区别。
当加载new.html.erb视图时,:post
工作,而@post
不工作。以下是相关视图和控制器:
This is Post's new.html.erb
<%= form_for(:post) do |f| %>
<%= f.text_area :note, value: "Say something" %><br>
<%= f.submit "Post" %>
<% end %>
PostController:
class PostsController < ApplicationController
before_action :signed_in_user, only: [:new, :create]
def index
@posts = Post.all
end
def new
end
def create
@post = current_user.posts.build
puts "This is #{@post.user_id} user"
redirect_to posts_path if @post.save #post/index.html.erb
end
def destroy
end
private
def signed_in_user
redirect_to signout_path, notice: "Please sign in." unless signed_in?
end
end
:post
将被Rails翻译为"使我成为一个新的Post对象并用它构建表单"。要使用@post
,您首先需要在控制器操作中对其进行初始化,即
def new
@post = Post.new
end
您应该使用@post
,因为在呈现表单(设置值、构建相关对象等)之前,您通常会想要进行一些初始化
如果你想将Post与User关联(使用current_User),你可以通过多种方式:
- @post.user_id=current_user.id
- @post.user=当前用户
- @post=current_user.posts.build(params…)
实际上,第三种方法是最好的方法。
此外,在创建/更新操作中,请始终记住将创建的对象与current_user关联,因此在用户发送表单后。将user_id作为表单字段显然可以允许用户更改它!