问题
Hey guys, first question here.
I have a couple of Products and Users that can put those Products on Wishlists. A User can have many Wishlists (for different purposes). Products can be added to Wishlists, but there's additional information involved: you have to specify an amount of a certain Product. This logic is used in the Inclusion, which has a field quantity.
Class Wishlist
belongs_to :user # User class is irrelevant here
has_many :inclusions
has_many :products, :through => :inclusions
end
Class Product
has_many :inclusions
has_many :wishlists, :through => :inclusions
end
Class Inclusion
belongs_to :product
belongs_to :wishlist
end
This is all working great, but now for the real question. Wishlists should be edited through textareas. The syntax is simple: quantity productname. All users use this syntax. For example, editing a Wishlist should look like this:
<textarea>
1 Bicycle
4 Shoe
1 Telephone
</textarea>
When the form is submitted, all the logic should be dealt with behind the scenes. So if the "1 Telephone" is taken off, the Inclusion should be destroyed. If a line is added or modified, the corresponding Inclusion should be created or updated, so that the database is synchronized with the contents of that textarea.
I have searched high and low, but could not find a solution for this. Thanks in advance!
回答1:
This is a bad idea, but for the sake of letting you learn from your own mistakes…
- Wrap your textarea-data attribute setter method to include functionality to…
- Parse out the relevant information from each line in the text area and…
- Call the original setter method for each.
- Do the opposite on the getter.
Your validations, associations, etc. all still work, and your logic to handle this is neatly packaged so that you can easily throw it away later if/when you run into problems.
来源:https://stackoverflow.com/questions/5724047/rails-using-a-textarea-for-has-many-relationship