Question

Oh so please bear with me... I have a model for bookings and a model for drivers. A driver has many bookings and a booking belongs to a driver.

When adding or editing a booking, I want the user to be able to type the username of the driver. Usernames are unique and easier for the end user than giving each driver a number.

Now this is how I have done it:

def create
  if params[:booking][:driver].empty? 
    params[:booking][:driver] = nil 
  else
    @driver = Driver.find(:first, :conditions => { :username => params[:booking][:driver] })
    params[:booking][:driver] = @driver
  end

This code works fine for submitting, but when the form is loaded, it shows the reference of the object (eg. #) and I need it to show the username. How can I change <%= f.text_field :driver %> in the form_for in the edit view to take the value of the drivers username?

Am I going about this the right way, or is there a dead easy, rails way to do what I need?

Was it helpful?

Solution

"but when the form is loaded" do you mean when it fails to create or when you are editing? Can you post post your full update and create actions please.

params[:booking][:driver] = @driver.username should populate your parameter with a string instead of an object, although I'm not sure this is really what you want to do. Instead of setting it to nil if its blank, just leave it blank, nil is an object which maybe why you are seeing the '#'

What you're doing here doesn't seem right, it probably makes more sense to just stick with the select box of drivers anyway, where the field is the driver_id. If you really want to use a text box then I'll help you out? Just post your code first.

Have you seen this? It should help guide you a little more:

http://railscasts.com/episodes/57-create-model-through-text-field

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top