【问题标题】:simple_form not saving contentsimple_form 不保存内容
【发布时间】:2015-09-07 23:43:38
【问题描述】:

我正在尝试使用 simple_form 创建一个简单的博客应用程序

在我的 new.html.erb for Post 中,我有以下代码

<h3>Write your blog post here</h3>
<%= simple_form_for @post do |f| %>
  <%= f.input :content %><br>
  <%= f.submit %>
<% end %>

在 index.html.erb 中,我得到了

<%= @posts.each do |post| %>
  <p>Post: <%= post.content %></p>
<% end %>

但是,我在 Post 的索引页面上收到以下内容

[#<Post id: 1, created_at: "2015-09-07 23:07:54", updated_at: "2015-09-07 23:07:54", content: nil>, #<Post id: 2, created_at: "2015-09-07 23:07:54", updated_at: "2015-09-07 23:07:54", content: nil>, #<Post id: 3, created_at: "2015-09-07 23:08:11", updated_at: "2015-09-07 23:08:11", content: nil>,

这是我的后期控制器

  def index
    @posts = Post.all
  end

  def show
    @post = Post.find(params[:id])
  end

  def new
    @post = Post.new
  end

  def create
    @post = Post.new(params[post_params])
      if @post.save
        success = true
        message = "Nice!"
      else
        success = false
        message = "Sucks!"
      end
      redirect_to root_path
  end

  private

  def post_params
    params.require(:post).permit(:content)
  end
end

这是我的模型

class Post < ActiveRecord::Base
  belongs_to :user
end

最后,将内容列添加到 Post 的迁移

class AddContentToPosts < ActiveRecord::Migration
  def change
    add_column :posts, :content, :string
  end
end

在我的帖子中输入文本后,我可以创建它。但我不确定它是否被保存为内容为“nil”。这非常令人沮丧,因为这似乎是一个非常简单的问题。经过数小时试图弄清楚发生了什么,在这里寻求帮助...... 谢谢!

【问题讨论】:

    标签: ruby-on-rails simple-form


    【解决方案1】:

    你有两个问题:

    首先,这一行:

    <%= @posts.each do |post| %>
    

    需要&lt;%,而不是&lt;%=

    &lt;%= 输出表达式的结果。 array.each 的结果是一个数组,这就是你在浏览器中看到的。

    第二,你对params的访问是错误的。你正在使用

    @post = Post.new(params[post_params])
    

    您使用params[:post],或者您使用post_params,但您不能同时使用这两种方法。您正在尝试使用post_params 的返回值,它是键和值的哈希,作为键 再次访问params。您需要以下任何一种:

    @post = Post.new(params[:post])
    # or
    @post = Post.new(post_params)
    

    【讨论】:

    • 当我删除“=”符号时,没有数据显示。现在它只是显示为空白..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-03
    • 2018-01-15
    • 1970-01-01
    • 1970-01-01
    • 2014-03-17
    相关资源
    最近更新 更多