Rails:使用 Textarea 表示 :has_many 关系
大家好,第一个问题在这里。
我有一些产品和用户可以将这些产品放入愿望清单。 用户可以有多个愿望清单(用于不同目的)。 产品可以添加到愿望清单,但涉及其他信息:您必须指定特定产品的数量。此逻辑用于包含字段,其中包含一个字段数量。
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
这一切都很好,但现在是真正的问题了。 愿望清单应通过文本区域进行编辑。语法很简单:数量产品名称。 所有用户都使用此语法。 例如,编辑愿望清单应如下所示:
<textarea>
1 Bicycle
4 Shoe
1 Telephone
</textarea>
提交表单时,所有逻辑都应在幕后处理。因此,如果“1 电话”被取下,那么内含物就会被破坏。如果添加或修改了一行,则应创建或更新相应的包含,以便数据库与该文本区域的内容同步。
我四处搜寻,但找不到解决方案。 提前致谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是一个坏主意,但是为了让您从自己的错误中吸取教训...
您的验证、关联等仍然有效,并且处理这些问题的逻辑被整齐地打包,以便您以后遇到问题时可以轻松地丢弃它。
This is a bad idea, but for the sake of letting you learn from your own mistakes…
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.