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

前端 未结 2 1769
说谎
说谎 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条回答
  •  梦毁少年i
    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
    

提交回复
热议问题