I\'m new to rails and I\'m kind of stuck with this design problem, that might be easy to solve, but I don\'t get anywhere: I have two different kinds of advertisements: high
fl00r has a good solution, however I would make one adjustment.
This may or may not be required in your case. It depends on what behavior is changing in your STI models, especially validations & lifecycle hooks.
Add a private method to your controller to convert your type param to the actual class constant you want to use:
def ad_type
params[:type].constantize
end
The above is insecure, however. Add a whitelist of types:
def ad_types
[MyType, MyType2]
end
def ad_type
params[:type].constantize if params[:type].in? ad_types
end
More on the rails constantize method here: http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-constantize
Then in the controller actions you can do:
def new
ad_type.new
end
def create
ad_type.new(params)
# ...
end
def index
ad_type.all
end
And now you are using the actual class with the correct behavior instead of the parent class with the attribute type set.