[英]Rails 2 way association not functioning
我有点问题。 我一直在开发一个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和An 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'表的'number'字段
我希望我已经清楚地解释了我的问题。 如果需要其他信息,请告诉我。 急切等待一些回复! :)
第一编辑:
当我在sqlite3数据库浏览器中查看我的'products'表时,ijn_id的列存在,但由于某种原因,没有条目。 这是一个截图:
问题是你已经定义了一个Product
has_many
:ijns
。 这与具有您架构中的ijn_id
的产品冲突。
因此,当您尝试执行product.ijn
您会收到错误消息。
编辑:
如果产品真的有很多ijns,那么ijn_id
对ActiveRecord和数据库毫无意义。 他们不知道它应该引用哪个。 我怀疑你希望它引用分配给产品的最后一个ijn。
在这种情况下,一种解决方案是将属性更改为类似current_ijn_id
。 每次需要更新时,您都必须手动分配值。
或者你可以做product.ijns.last
。 问题是你需要确保.last
都会给你正确的ijn。 例如,如果由于某种原因你将产品“回滚”到旧的ijn,它可能不起作用。
似乎你让这比你需要的更复杂:
表
您的ijn
号码就像SKU (您的系统的唯一标识符)对吗? 由于它是产品的属性,为什么不将它放在产品表中:
#products table
id | ijn | name | created_at | updated_at
这立即否定了对额外表的要求(也保存了查询)
额外
如果你想调用额外的数据为您product
,您将需要一个表专为数据
对我而言, model
是具有特定目的的数据集合。 拥有ijn
的模型并不能构成这一点
#app/models/products.rb
Class Product < ActiveRecord::Base
has_one :profile, class_name: "ProductProfile"
end
#app/models/product_profile.rb
Class ProductProfile < ActiveRecord::Base
belongs_to :product
end
这将允许您调用类似@product.profile.quantity
或类似的东西
puts Product.first.ijn.number
这应该根据你想要做的工作。
非常感谢你的帮助...我做了一些阅读并找到了我的解决方案..对于像我一样的一对多关系,你只需要在一边提供引用表的'id',即包括'ijn'表中的'product_id'列。 我删除了'products'表中的'ijn_id'列,并在我的'ProductsController'中包含了一行代码。 这里是:
...
def show
@product = Product.find(params[:id])
#getting the related IJN
@ijn = Ijn.find(:all, :conditions => ['product_id = ?',@product])
end
...
现在,在视图中,只需执行即可引用关联的产品名称
<% @ijn.map do |i| %>
<tr>
<td><%=i.number %></td>
<td><%= i.quantity %></td>
<td><%= i.name %></td> #this returs the assocaiated product name
<td><%= Date::MONTHNAMES[i.product.created_at.month] %></td>
<td>placeholder</td>
<td>placeholder</td>
</tr>
<% end %>
返回产品名称和关联的IJN列表。 我没有在上面的代码中添加任何样式。
我希望这有助于其他遇到类似问题的人。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.