code4j
code4j

Reputation: 4636

How to to really type cast a model in Rails?

I have a Item as superclass and there are two subclasses under it.

When the user input the information at the first time, the input parameters are included in the hash of params[:item]. And I instantiate the concrete type according to the input.

# instantitate the concrete type according to the input
type_of_item = Object::const_get(inputs[:type])
@item = type_of_item.new

When the validation is failed, I put the user back to the new page. The user input the data again

However, this time, the input parameters will be included in the hash of params[:bidding_item] or params[:direct_item where bidding_item and direct_item are the subclass of Item

I try to do something like:

format.html do
  @item.becomes(Item)
  render :action=>"new"
end

I hope every time the input parameters will be include in params[:item] so that I can get the data in the same way at every time, but it doesn't work.

Now, I solve my problem with. But I think it is not a good practice at all.

# form input
inputs = params[:item] || params[:bidding_item] || params[:direct_item]

Upvotes: 0

Views: 135

Answers (1)

Andrew Hubbs
Andrew Hubbs

Reputation: 9426

In your new view file you can add the :as option to the form_for tag.

form_for @item, :as => :item do |form|

This will mean that the parameters will always come through as params[:item] independent of what the object type is.

Upvotes: 2

Related Questions