【问题标题】:What's the difference between @post and :post in form_for?@post 和 form_for 中的 :post 有什么区别?
【发布时间】:2014-04-11 22:51:55
【问题描述】:

我已尝试通读 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 %>

后控制器:

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

【问题讨论】:

标签: ruby-on-rails instance-variables form-for


【解决方案1】:

:post 将被 Rails 翻译为“让我成为一个新的 Post 对象并用它构建表单”。 要使用@post,您首先需要在控制器操作中对其进行初始化,即

def new
  @post = Post.new
end

您应该使用@post,因为通常您最终会想要在呈现表单之前进行一些初始化(设置值、构建关联对象等)

如果您想将 Post 与用户关联(使用 current_user),您可以通过多种方式进行:

  1. @post.user_id = current_user.id
  2. @post.user = current_user
  3. @post = current_user.posts.build(params...)

实际上,第三种方法是最好的方法。

此外,请始终记住在创建/更新操作中将创建的对象与 current_user 相关联,以便在用户发送表单之后。将 user_id 作为表单字段显然会允许用户更改它!

【讨论】:

  • 作为后续问题,如何将@post的foreign_key设置为user_id?会是@post.user_id = current_user.id吗?
  • 是的,完全正确。请记住仅在创建操作中执行此操作,因此用户无法篡改值。请参阅我的更新答案。
猜你喜欢
  • 2011-03-11
  • 2013-10-06
  • 1970-01-01
  • 1970-01-01
  • 2015-09-14
  • 2017-03-15
  • 2015-08-03
  • 1970-01-01
  • 2011-10-11
相关资源
最近更新 更多