开发者

Establishing a has_many relationship in Rails

I'm having trouble creating an application in Rails.

This application has two models, one to represent companies and the other to represent products. Each company sells zero or more products and I'm looking to capture this relationship in the model. Here's what I've got so far:

I created the models by running the generator:

script/generate scaffold company name:string product_id:integer

script/generate scaffold product name:string

I added the following line to the company model to show that each company can have multiple products:

has_many :products

I added the following line to the product model:

belongs_to :company

I created some sample data in YAML files. The sample data for the companies is:

microsoft:
  name: Microsoft
  product_id: [1, 3]

google:
  name: Google
  product_id: [2, 4]

And the sample data for the products is:

word:
  id: 1
  name: Word

earth
  id: 2
  name: Earth

excel:
  id: 3
  name: Excel

chrome:
  id: 4
  name: Chrome

I then loaded the sample data:

rake db:fixtures:load

I'm then trying to print all of the products for a company in the company view:

<% if @company.product_id %>
<% for product in @company.product_id %>
  <tr>
    <td><%=h product.name %></td>
  </tr>
<% end %>
<% end %&开发者_开发技巧gt;

This is where I get an error. Any ideas? I'm not sure what the problem is. For all I know it could be in how I generated the models or established their relationships. Or it could be in how I'm attempting to print the information in the view.


First, you've got your fields set up wrong. has_many and belong_to require that it be products that has company_id rather than the other way around. For a one-to-many relationship, the foreign key always needs to be placed on the "many" side of the equation.

And then you want this instead:

<% for product in @company.products %>
  <tr>
    <td><%=h product.name %></td>
  </tr>
<% end %>


You don't say what your error is, but I believe that your yml file isn't quite right.

Last time I checked, this was not possible:

microsoft:
  name: Microsoft
  product_id: [1, 3]

The product_id: "list" will only accept "tags" -> Word, Excel. But then it will generate "weird" ids (using the hashes of the tag strings). So it will not work very well either.

And, as others said, it will be much easier if you put a client_id in products. It's just how databases work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜