Rails - 简单的表单,不保存数据库的输入

时间:2018-05-23 11:28:27

标签: ruby-on-rails ruby simple-form simple-form-for

我不知道为什么但是我无法将表单输入保存到数据库中,到目前为止我找不到任何答案:),但它适用于使用控制台创建帖子。

  Started POST "/posts" for 127.0.0.1 at 2018-05-23 14:04:32 +0300
Processing by PostsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"B19yVi1jHtg7068SKFbI3tj28THNdfgGYwUSN+e79Vt/o0ivDUl0D4i71PuLKlZf1wxnEJMVnp+GmH/HcxE6cQ==", "post"=>{"category_id"=>"2", "title"=>"asfaf", "content"=>"asfkja", "photo_cache"=>""}, "commit"=>"Create Post"}
Unpermitted parameter: :photo_cache
  User Load (0.8ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 1], ["LIMIT", 1]]
   (0.5ms)  BEGIN
  Category Load (0.5ms)  SELECT  "categories".* FROM "categories" WHERE "categories"."id" = $1 LIMIT $2  [["id", 2], ["LIMIT", 1]]
   (0.4ms)  ROLLBACK

<%= simple_form_for(@post) do |f| %>
  <%= f.collection_select(:category_id, Category.all, :id, :name, {prompt: "Choose a category" }) %><br>
  <%= f.label :title %><br>
  <%= f.text_field :title, placeholder: "Type the post title here" %><br>
  <%= f.label :content %><br>
  <%= f.text_area :content, placeholder: "Type the post text here" %><br>
  <%= f.input :photo %>
  <%= f.input :photo_cache, as: :hidden %><br>
  <%= f.submit %>
<% end %>

def new
  @post = Post.new
  authorize @post
end

def create
  @post = Post.new(post_params)
  authorize @post
  if @post.save
    redirect_to @post, notice: "The post was created!"
  else
    render 'new'
  end
end

def post_params 
  params.require(:post).permit(:title, :content, :category_id, :photo, :user_id)
end

class Post < ApplicationRecord
  validates :title, :content, :category_id, presence: true
  belongs_to :category
  belongs_to :user
  mount_uploader :photo, PhotoUploader
end

2 个答案:

答案 0 :(得分:2)

控制台输出指出原因 - 您在不允许的情况下传递photo_cache参数:

Unpermitted parameter: :photo_cache

因此,只需将:photo_cache添加到permit列表:

params.require(:post).permit(..., :photo_cache)

更新:如果Post模型属于User,则应该有外键约束,并且必须user_id参数传递给Post.create。 在实际应用程序中,Devise之类的内容用于身份验证,控制器类似于:

class PostsController < ApplicationController    
  before_action :authenticate_user!

  def create
    post = current_user.posts.create!(create_params)
    # post = Post.new(create_params.merge(user: current_user))
    # ...
  end
end

答案 1 :(得分:0)

基本上有助于改变创建方法

def create
 @post = current_user.posts.new(post_params)
 authorize @post
 if @post.save
  redirect_to @post, notice: "The post was created!"
 else
  render 'new'
 end
end