问题描述
大家好,第一个问题.
我有几个产品和用户可以将这些产品放入心愿单.一个用户可以有多个愿望清单(出于不同的目的).产品可以添加到愿望清单"中,但是还涉及其他信息:您必须指定某个产品的数量.此逻辑用于包含范围为 quantity 的Inclusion.
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>
提交表单时,所有逻辑都应在幕后处理.因此,如果摘下"1电话",则包含物应被销毁.如果添加或修改了一行,则应创建或更新相应的包含,以使数据库与该文本区域的内容同步.
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!
推荐答案
这是一个坏主意,但是为了让您从自己的错误中学习……
This is a bad idea, but for the sake of letting you learn from your own mistakes…
- 包装您的textarea-data属性设置器方法以包括以下功能……
- 从文本区域的每一行中解析出相关信息,然后…
- 为每个调用原始的setter方法.
- 在吸气剂上做相反的事情.
您的验证,关联等都仍然有效,并且处理此问题的逻辑已经整齐打包,以便以后遇到问题时可以轻松地将其丢弃.
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.
这篇关于Rails:将文本区域用于:has_many关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!