activerecord - Rails: working with associations and join-table in a many-to-many relationship -


I have a model with a user model and a product I have "has_and_belongs_to_many" in many associations and in both models

I understand that this allows me to work with relationships like this:

  user = User: The first user.Users  

and

  Shows all products purchased by product = product. The first product .Users # shows those users who have bought that product  

but there may be a product that has not been purchased by any user, so this product Products will be in the table, but user_products join-table

How do I return only user-product organizations that are saved in the included table?

Also, say I want to make a product as well as it defines that it has been bought - already and another user I thought of:

  User.all [0..1] .each {| Usr | Usr.product.create (name: "TV")}  

Is this the correct way to point out an affiliation and prepare a table that connects it to the record ?

What will happen, as I said above, I have a product that is in the Products table but still no user has bought it, and Now the user buys it: How can I express it so that later I

  user.products  

Can I see that product ?

How do I return only user-product organizations, which are saved in these Table?

You can not do this, because you have decided to use is_ and_belgons_to_yam where the inserted table is not available at all has_many via < / Code> Consider using the relationship.

Is it correct to point to an affiliation and for this to prepare a table that is associated with the record?

It should be:

  User.limit (2) .each {| Usr | Usr.products.create (name: "TV")}  

or

  User.limit (2) .each {| Usr | Usr.products & lt; & Lt; What happened, as I said above, what would happen if I had a product that is in the product table, but no user had bought it so far. And now a user buys it: How can I express it so that later I   

just user.products.reload


Comments

Popular posts from this blog

java - Can't add JTree to JPanel of a JInternalFrame -

javascript - data.match(var) not working it seems -

javascript - How can I pause a jQuery .each() loop, while waiting for user input? -