How to update a model's attribute with a virtual attribute?

前端 未结 2 1768
说谎
说谎 2021-01-15 15:27

I have a model named UserPrice which has the attribute :purchase_date(a date_select) in its table. With my form I can create multiple user_prices a

相关标签:
2条回答
  • 2021-01-15 16:11

    This is a case of trying to do in a model what is better left to the controller. All you're trying to do here is to auto-assign a certain attribute on creation from a parameter not directly tied to your model. But you're not even passing that extra parameter to the model anywhere - you're creating your model instances from the user_prices parts of the parameter hash, but the user_price sub-hash is not used anywhere. In any case, this is behavior that is more closely related to the view and action taken than the model, so keep it in the controller.

    Try this:

    1. Throw out the virtual attribute, and get rid of the whole after_save callback stuff
    2. Throw away the user_prices method in your model
    3. Change the all_dates attribute name back to purchase_date in the form

    Then your parameter hash should look like this:

    {"user_price"=> { 
      "purchase_date(2i)"=>"10", 
      "purchase_date(3i)"=>"27", 
      "purchase_date(1i)"=>"2011"
    }, 
    "user_prices"=>
    {
      "0"=>{"product_name"=>"Item1", "store"=>"Apple Store","price"=>"6"}, 
      "1"=>{"product_name"=>"Item2", "store"=>"Apple Store", "price"=>"7"}
    }}
    

    All that's left to do is to merge the single user_price attributeS into each user_prices sub-hash in your create_multiple action. Replace the first line in that action with this:

    @user_prices = params[:user_prices].values.collect do |attributes| 
      UserPrice.new(attributes.merge(params[:user_price])) 
    end
    
    0 讨论(0)
  • 2021-01-15 16:24

    I'm not sure why you are even using that virtual attribute is there more to this implementation? If you are just trying to save an associated model, you might simply want a accepts_nested_attributes_for :user_prices in your User model

    This works great and many developers use this method, so it's nice to know for working on other projects as well as for the people who might end up maintaining yours.

    http://railscasts.com/episodes/196-nested-model-form-part-1

    http://railscasts.com/episodes/197-nested-model-form-part-2

    0 讨论(0)
提交回复
热议问题