I’m fairly new to Ruby on Rails and within my app the user is able to create a ‘build’ record that will only be saved if the entire record is unique. If a user tries to create an existing ‘build’ / record and the validation fails, I need to be able to redirect that user to the existing record.
As I have stated, I am a novice and made a valiant attempt at using the parameters passed to my create action as so:
def create
@build = Build.new(params[:build])
if @build.save
redirect_to :action => 'view', :id => @build.id
else
@bexist = Build.find(params[:build])
redirect_to :action => 'view', :id => @bexist.id
end
end
Clearly this isn’t correct… I also tried to look into callbacks with after_validation, but wasn’t sure how to access or even store the existing record’s id. Anyone have any suggestions?
You need the attribute/value hash to be passed as the :conditions option, and you need to specify :first, :last, or :all as the first argument.
Alternatively, you can use the #first method instead of using #find with a :first argument.
In Rails 3, you have yet another option…