【发布时间】:2014-01-26 08:02:53
【问题描述】:
我有一点问题。我一直在开发 Rails 应用程序并遇到了一个我无法解决的问题。
到目前为止,我的应用程序允许用户将产品详细信息输入数据库(存储在“产品表”中)这是我正在使用的数据库的架构。
ActiveRecord::Schema.define(version: 20140126073333) do
create_table "ijns", force: true do |t|
t.integer "number"
t.integer "product_id"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "quantity"
end
add_index "ijns", ["number"], name: "index_ijns_on_number"
create_table "products", force: true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "ijn_id"
end
add_index "products", ["name"], name: "index_products_on_name"
end
还有一个名为“ijns”的表,它为每个产品分配一个唯一标识符。这个 ijn 没有被故意设为主键,因为我不希望它成为自动递增的值。
B/w IJN 和 Product 的关系是:
一个产品 has_many ijns 和 一个 ijn 属于一个产品。
这是我的产品模型
class Product < ActiveRecord::Base
has_many :ijns
validates :name, presence: true, length: { minimum: 10 }, uniqueness: true
end
IJN 模型。
class Ijn < ActiveRecord::Base
belongs_to :product
validates :number, presence: true, uniqueness: true, length: { is: 4 }, numericality: { only_integer: true }
validates :product_id, presence: true
validates :quantity, presence: true
end
我能够从 IJN 方面获得关联,即,我能够通过使用以下方式访问产品模型的字段:
@ijn.product.name
但我无法从产品型号访问“ijns”表的“编号”字段
我希望我已经清楚地解释了我的问题。如果需要其他信息,请告诉我。急切地等待一些答复! :)
第一次编辑:
当我在 sqlite3 数据库浏览器中查看我的“产品”表时,ijn_id 列存在,但由于某种原因没有条目。这是截图:
【问题讨论】:
-
你试过什么?如果你写
@product.ijns,你会得到什么?NoMethodError还是别的什么? -
是的罗宾,我得到一个 NoMethodError
标签: ruby-on-rails ruby model-associations