开发者

A field in a rails form to select a 'belongs_to' object

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?


"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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜