Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Dan's answer above is correct, but as a simpler version of it, to create the association you're describing you need:</p> <pre><code>class Company &lt; ActiveRecord::Base has_many :products has_many :users end class Product &lt; ActiveRecord::Base belongs_to :company end class User &lt; ActiveRecord::Base belongs_to :company end </code></pre> <p>The Product and User tables need a column called <code>company_id</code>.</p> <p>That's it! Now ActiveRecord will associate the objects intelligently on your behalf, and you can do things like:</p> <pre><code>@product = Product.new(params[:product]) @product.company = current_user.company @product.save </code></pre> <p>The best way to understand how all these relationships work is to play with them in the console. Try things like:</p> <pre><code>Company.first.products Company.find(2).products Company.find_by_name('Acme').products.order('price DESC') User.last.products.where(...) </code></pre> <p>and so on...</p> <p>Lastly, a thought: You would benefit immensely from reading an introductory book on Rails. I recommend '<a href="http://rads.stackoverflow.com/amzn/click/1430224339" rel="nofollow">Beginning Rails 3</a>'. It's a fast read, you could work through it in a weekend, and it will make the big picture of how and WHY rails works the way it works very clear to you. The time spent reading the book will QUADRUPLE your productivity and the speed at which you learn more advanced stuff, because you'll be starting with a solid foundation and approaching problems "the rails way."</p> <p>Your problem today was definitely a case of "you're doing it wrong", which doesn't mean there's anything wrong with your logic, just that you're making a simple problem much more difficult by trying to reinvent the wheel unnecessarily. Learning "the rails way" will make you much more productive, and will make the whole thing a lot more fun.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload