我在 Rails 中创建应用程序时遇到问题。
这个应用程序有两个模型,一个代表公司,另一个代表产品。每家公司都销售零种或多种产品,我希望在模型中捕捉这种关系。到目前为止,这是我得到的:
我通过运行生成器创建了模型:
script/generate scaffold company name:string product_id:integer
script/generate scaffold product name:string
我在公司模型中添加了以下行以表明每个公司可以有多个产品:
has_many :products
我在产品模型中添加了以下行:
belongs_to :company
我在 YAML 文件中创建了一些示例数据。公司的示例数据是:
microsoft:
name: Microsoft
product_id: [1, 3]
google:
name: Google
product_id: [2, 4]
产品的样本数据是:
word:
id: 1
name: Word
earth
id: 2
name: Earth
excel:
id: 3
name: Excel
chrome:
id: 4
name: Chrome
然后我加载了示例数据:
rake db:fixtures:load
然后我尝试在公司 View 中打印公司的所有产品:
<% if @company.product_id %>
<% for product in @company.product_id %>
<tr>
<td><%=h product.name %></td>
</tr>
<% end %>
<% end %>
这是我遇到错误的地方。有任何想法吗?我不确定是什么问题。据我所知,这可能与我生成模型或建立模型关系的方式有关。或者可能与我尝试在 View 中打印信息的方式有关。
最佳答案
首先,您的字段设置有误。 has_many
和 belong_to
要求它是具有 company_id
的 products
,而不是相反。对于一对多关系,外键始终需要放在等式的“多”侧。
然后你想要这个:
<% for product in @company.products %>
<tr>
<td><%=h product.name %></td>
</tr>
<% end %>
关于ruby-on-rails - 在 Rails 中建立 has_many 关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1834593/