Rails: Using a Textarea for :has_many relationship

ぃ、小莉子 提交于 2020-01-06 12:53:11

问题


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…

  1. Wrap your textarea-data attribute setter method to include functionality to…
  2. Parse out the relevant information from each line in the text area and…
  3. Call the original setter method for each.
  4. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!