简体   繁体   中英

How do you create a new row for a block in a database or a new model for each in Rails?

I'm creating a baby stork party / baby shower gift registry app with Rails where the mom to bee creates a registry and the other friends can nominate gifts etc.

I'm using Rails and after studying a few Rails books I'm getting to intermediate. The problem is I can't figure out how to create a fixed baby registry where the mom can just choose quantity, color, brand next to each product category and save.

I created the model Registry and the columns quantity, brand, color etc. After a while I figured this won't work as how will a name each category (row) for those columns and keep it fixed (in a sense) and separate almost like a form? It almost feels like I need a separate model for each category but that can't be the most effective way?

Its really hard to explain, but I'm stuck or missing something?

It sounds like you are describing a many-to-many relationship between a registry item, and a trait. So an item can have many traits (color, quality, brand) and a trait can have many items (so you can find all the items by color, quality, etc).

Checkout:

http://guides.rubyonrails.org/association_basics.html#the-has_and_belongs_to_many-association

class Color
  has_and_belongs_to_many :items
end

class Items
  has_and_belongs_to_many :colors
end

Will allow you to do things like:

item = Item.find 1
color = Color.find_by_name 'blue'
item.colors << color

# all the items for a color
color.items    # item 1

# all the colors for an item
item.colors    # blue

Structuring your form(s) to support this will require some work, I suggest googling around for examples.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM