【问题标题】:Rails : can't write unknown attribute `url'Rails:无法编写未知属性“url”
【发布时间】:2013-11-05 12:49:37
【问题描述】:

我是 ruby​​ on rails 的新手,我正在通过创建博客来学习。我无法保存到我的博客表中,并且收到此错误“无法写入未知属性 url”

博客迁移: db/migrate/

class CreateBlogs < ActiveRecord::Migration
  def change
    create_table :blogs do |t|
      t.string :title
      t.text :description
      t.string :slug
      t.timestamps
    end
  end
end

博客模型: /app/models/blogs.rb

class Blogs < ActiveRecord::Base
  acts_as_url :title
  def to_param
    url
  end
  validates :title, presence:true
end

博客控制器: /app/controllers/blogs_controller.rb

class BlogsController < ApplicationController
  before_action :require_login

  def new
    @blogs = Blogs.new
  end

  def show
    @blogs = Blogs.find_by_url(params[:id])
  end

  def create
    @blogs = Blogs.new(blogs_params)
    if @blogs.save

      flash[:success] = "Your Blog has been created."

      redirect_to home_path

    else
      render 'new'
    end
  end

  def blogs_params
    params.require(:blogs).permit(:title,:description)
  end


  private

  def require_login
    unless signed_in?
      flash[:error] = "You must be logged in to create a new Blog"
      redirect_to signin_path
    end
  end
end

博客表单:/app/views/blogs/new.html.erb

块引用

<%= form_for @blogs, url: blogs_path do |f| %><br/>
<%= render 'shared/error_messages_blogs' %><br/>
<%= f.label :title %><br/>
<%= f.text_field :title %><br/>
<%= f.label :description %><br/>
<%= f.text_area :description %><br/>
<%= f.submit "Submit Blog", class: "btn btn-large btn-primary" %><br/>
<% end %><br/>

我还在我的 routes.rb 文件中添加了“resources :blogs”。

我在控制器中收到此错误

如果@blogs.save

【问题讨论】:

  • 请修正您的代码。删除那些乱七八糟的东西,然后粘贴到一个新副本中,然后全选并点击{} 按钮进行格式化。
  • 我重新格式化了所有内容,但是查看我编辑的人决定拒绝它们。所以又是一团糟:(
  • 我重新格式化了。对不起,我是 stackoverflow 的新手 :)
  • 看看 Markdown ~ 那是 StackOverflow(和许多其他像 GitHub)使用的语法语言。

标签: ruby-on-rails ruby-on-rails-3 activerecord


【解决方案1】:

该错误准确地说明了您的问题是什么:"can't write unknown attribute url" 暗示您尝试在 def to_paramsBlogs 模型中访问的 url 变量是未知的,因为您希望将其存储在 @987654326 @。 acts_as_url 方法由stringex gem 添加和使用,因为您没有收到有关未知方法acts_as_url 的错误,所以必须成功安装gem,只是配置错误

进一步查看 gem 的文档,gem 将 url 的值设置为模型中应该已经存在的 db 列。从您的数据库架构中,url 应该使用列 slug 而不是 url(stringex 的默认值)。将您的博客类更改为以下应该解决问题:

class Blogs < ActiveRecord::Base
  acts_as_url :title, url_attribute: :slug
  def to_param
    slug
  end
  validates :title, presence:true
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-07
    • 2021-01-14
    • 2014-01-11
    • 2019-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多