【问题标题】:UnknownAttributeError in ContactsController#createContactsController#create 中的 UnknownAttributeError
【发布时间】:2016-03-07 21:09:46
【问题描述】:

当我正在学习 Ruby 课程时,在保存到 db 的表单上按提交后出现此错误。我也已经尝试过rake:db migrate 无济于事。

ActiveRecord::UnknownAttributeError in ContactsController#create
unknown attribute: comments

提取的源代码(第 7 行附近): 5 6 7 8 9 10

定义创建 @contact = Contact.new(contact_params)

if @contact.save
  redirect_to new_contact_path, notice: "Message sent."

我的联系人controler.rb 代码

class ContactsController < ApplicationController

 def new
 @contact = Contact.new
 end

 def create
    @contact = Contact.new(contact_params)

    if @contact.save
      redirect_to new_contact_path, notice: "Message sent."
    else
      redirect_to new_contact_path, notice: "Error occurred."
    end
 end

 private
    def contact_params
      params.require(:contact).permit(:name, :email, :comments)
    end
end

我的联系人.rb

class Contact < ActiveRecord::Base
    def name
    end

    def email
    end

    def comments
    end

end

--------------

    class CreateContacts < ActiveRecord::Migration
 def change
    create_table :contacts do |t|
      t.string :name
      t.string :email
      t.text :commments

      t.timestamps
    end
 end
end

【问题讨论】:

    标签: html ruby-on-rails-4 attributes


    【解决方案1】:

    在您的迁移文件中,cmets 列有 3m (:commments) 而不是两个

    def change 
         create_table :contacts do |t| 
                 t.string :name 
                 t.string :email 
                 t.text :commments
    
                 t.timestamps
    end
    

    现在您必须通过创建迁移来更改列 How can I rename a database column in a Ruby on Rails migration?

    【讨论】:

    • 感谢我能够使用这种方法,因为此时数据并不重要“在这种情况下,最好使用 rake db:rollback。然后编辑您的迁移并再次输入 rake db:migrate . 但是,如果您不想丢失列中的数据,请使用 rename_column。”
    • db:rollback 很好,如果您没有任何重要数据。很高兴它对您有用,祝您的应用好运;)
    【解决方案2】:

    :comments 是您的 Contact 模型中的 db 字段吗?它应该在这里工作:

    def 
        contact_params params.require(:contact).permit(:name, :email, :comments) 
    end
    

    【讨论】:

    • 感谢模型显示为:class Contact
    猜你喜欢
    • 2015-10-04
    • 2014-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多