Domanda

I have an ownership model that belongs to a product model and to a user model.

An ownership has the following parameters :

  • user_id (integer)
  • product_id (integer)
  • owning_date (datetime)
  • given_date (datetime)
  • current (boolean)
  • agreed (boolean)

A user is the owner of a product when current is true. current is true when owning_date is not nil, and given_date is nil.

I have an update method in my ownership controller that is defined like this :

def update
    @ownership = Ownership.find(params[:id])
    @ownership.update_attributes(ownership_params)
    respond_to do |format|
      format.html do
        flash[:success] = t('flash.success.ownership.update')
        redirect_to product_path(@ownership.product)
      end
      format.js
    end
  end

I created an agree button and a take button :

<%= form_for(ownership, remote: true) do |f| %>
  <div><%= f.hidden_field :agreed, value: true %></div>
  <%= f.submit "agree" %>
<% end %>


<%= form_for(ownership, remote: true) do |f| %>
  <div><%= f.hidden_field :owning_date, value: Time.now %></div>
  <%= f.submit "take" %>
<% end %>

Now I want to change the update method in my controller because when the user click on the take button, the given_date of the previous ownership must be changed to Time.now. But I don't want my update method to do that when the user click on the agree button.

I tried the following code but it didn't worked. After clicked on the button, there was two ownerships with current for the same product.

  def update
    @ownership = Ownership.find(params[:id])
    if @ownership.owning_date != params[:owning_date]
      @ownership.product.ownerships.find_by(current: true).update_attributes(given_date: Time.now, current: nil)
    end
    @ownership.update_attributes(ownership_params)
    respond_to do |format|
      format.html do
        flash[:success] = t('flash.success.ownership.update')
        redirect_to product_path(@ownership.product)
      end
      format.js
    end
  end

Do you have an idea ?

È stato utile?

Soluzione

Maybe you want to check witch form is submitted and do some action depending on user's choice?

Simple check like this in OwnershipCcontroller#update

if params[:commit] == 'take'
  # do some action
else
  # do another action
end
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top