为什么在 rails 的 ruby 中将空白数据插入到我的数据库中?

Why insert blank data into my database in ruby on rails?

我是 ruby rails 应用程序的新手,从最近几天开始,我一直在为将空白数据插入数据库而苦恼。

这是我的控制器:

@post = Post.create(created_at: Time.now, user_id: @user.id)

这是我的表格:

 <%= form_for :user, url: user_path(@user), action: :create, method: :post do |f| %>

   <%= f.text_field :title %>
   <%= f.text_area :description%>
   <%= f.text_field :location%>
   <%= f.submit %>
 <% end %>

我的模型:

class User< ActiveRecord::Base
   has_many :posts
end

class Post < ActiveRecord::Base
  belongs_to :user
end

拜托,这对我有很大帮助。

您需要将来自表单的数据传递给 create 方法。

将您的 create 操作更新为:

@post = @user.posts.create(user_params)

在控制器末尾添加以下方法:

private

# For strong parameters
def user_params
  params.require(:post).permit(:title, :description, :location)
end

不要忽略您需要了解以下内容:

  1. 您不需要手动传递 created_at 值。让框架为您处理。

  2. @user.posts.create 表示,您正在为 @user 创建 posts@user.posts.create 将 auto-populate 您的 user_id 列。

  3. 出于安全原因,您应该使用 strong parameters

进一步建议阅读:Rails Official Guide