Jason Varga
Jason Varga

Reputation: 1959

Get params from Model

I'm pretty sure there is a better way to do what I want to do, so please tell me.

I have an Item model that can either be sold to someone (have a sale_price and a buyer_id) or be passed (not sold to anyone - sale_price of zero and no buyer_id).

Until now I just relied on the user entering the appropriate price/buyer combination, but I'd like to add a second submit button to the Item edit form that just says 'pass'. (<input type="submit" name="pass" value="Pass" />).

Upon submission by pressing that button, I'd like to override whatever sale_price and buyer_id has been selected by the user and set them myself.

I assume I should do a :before_save in item.rb, but I don't know how to detect the button from the model - or if it's even possible (or advised).

Thanks

Upvotes: 1

Views: 5087

Answers (1)

Andre Bernardes
Andre Bernardes

Reputation: 1623

You can differentiate the commit type in your controller:

def create
  item = Item.new(params[:item])

  if params[:commit] == "Pass"
    item.sale_price = nil
    item.buyer_id = nil
  end

  if item.save
    # ...usual rails stuff
  end
end

Of course, if you have the commit type in the controller, you can pass it into the model with a virtual attribute and use callbacks if you like:

class Item < ActiveRecord:Model
  attr_accessor :pass

  before_save :reset_sale_price

  private

  def reset_sale_price
    if pass
      self.sale_price = nil
      self.buyer_id = nil
    end
  end
end

class ItemsController < ApplicationController

  def create
    item = Item.new(params[:item])
    item.pass = (params[:commit] == "Pass")

    if item.save
      #... standard rails stuff
    end
  end
end

Hope it helps. Cheers!

Upvotes: 4

Related Questions