【问题标题】:Belongs_to only recognized by console, not serverBelongs_to 只能被控制台识别,不能被服务器识别
【发布时间】:2013-04-20 08:03:47
【问题描述】:

我的项目遇到了一个非常奇怪的问题。我有 2 个模型,一个是 Link,另一个是 Category。我有一个索引视图,其中应列出所有链接以及相应的类别名称。运行服务器并尝试使用时

<%= link.category.name %>

我收到一个错误页面,内容如下:

undefined method `name' for nil:NilClass

但是当我打开控制台写:

link = Link.find(1) #there is currently only one link
link.category.name 

它返回正确的类别名称。

这是我的模型和 schema.rb:

class Link < ActiveRecord::Base
  attr_accessible :category_id, :description, :title, :url, :visible

  belongs_to :category

  scope :visible, lambda { where(visible: true) }
end

.

class Category < ActiveRecord::Base
  attr_accessible :name

  has_many :links

end

.

ActiveRecord::Schema.define(:version => 20130420070717) do

  create_table "categories", :force => true do |t|
    t.string   "name"
    t.datetime "created_at", :null => false
    t.datetime "updated_at", :null => false
  end

  add_index "categories", ["id"], :name => "index_categories_on_id"

  create_table "links", :force => true do |t|
    t.string   "title"
    t.text     "description"
    t.string   "url"
    t.integer  "category_id"
    t.boolean  "visible"
    t.datetime "created_at",  :null => false
    t.datetime "updated_at",  :null => false
  end

  add_index "links", ["category_id"], :name => "index_links_on_category_id"
  add_index "links", ["id"], :name => "index_links_on_id"
end

怎么会这样?非常感谢您的帮助!

【问题讨论】:

  • 您能否查看您的所有链接是否都与某个类别相关联?例如有一个由于某种原因不是 nil 的 category_id 吗?尝试这样做并告诉我它返回什么:Link.all.collect(&amp;:category_id).include?(nil)
  • 感谢您的快速响应!当我在控制台中执行它时,它返回 false。数据库中目前只有 1 个链接,它有一个正确的 category_id。
  • 嗯,那我不知道..你能显示你的视图代码吗?
  • 这将有助于查看相关控制器并查看索引操作的代码。
  • 我发现了问题,category_id 错误。对于我提供的错误信息,我深表歉意。我为这个问题添加了一个解决方案,也许我可以帮助其他面临同样问题的人。非常感谢您的帮助!

标签: ruby-on-rails foreign-keys entity-relationship models belongs-to


【解决方案1】:

也许我可以帮助其他面临同样问题的人。

category_id 是通过从数据库中查询现有类别的表单分配给链接的。

<%= f.select(:category_id, @categories.collect { |c| c.name }) %>

我要分配的类别的id = 1。从下拉菜单中选择类别后,link.category_id 为0,应该是1。

更新:

我通过以下方式修复了错误的索引:

<%= f.collection_select :category_id, @categories, :id, :name, :prompt => "Select a category" %>

【讨论】:

    猜你喜欢
    • 2022-01-06
    • 2021-05-14
    • 2010-11-01
    • 2021-11-22
    • 1970-01-01
    • 2012-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多