开发者

Rails - Allow a model to associate with existing objects or create a new one

Let's say I have a two models, Event and Person. An event has a coordinator that is a person:

class Event < ActiveRecord::Base
    belongs_to :coordinator, :class_name => 'Person', :foreign_key => 'coordinator_id'
    accepts_nested_attributes_for :coordinator
end

class Person < ActiveRecord::Base
    validates :name, :length => 20
end

In my form, I would 开发者_运维技巧like to let the user pick from existing People objects (let's say a list of radio buttons), but also have a text box to create a new Person (with the name entered in the text box).

How would I elegantly implement this? I can figure it out, but it involves a lot of ugly code in the Controller, and is a pain to validate.


I've done something similar in which the radio buttons set person[id] and then I just checked for the id.

So in my controller#create method:

if params[:person][:id]
   @person = Person.find(params[:person][:id])
else
   @person = Person.new(params[:person])
   #Handle saving @person here.
end

You may have to delete the id param in the elseblock if the form sends it even if nothing is selected.

Edit to answer validation question:

In the #Handle saving @person here. is where you'd do what you normally do for creating an object. Like:

if @person.save
  flash[:notice] = "User created successfully"
else
  render :action => 'new' # (or whatever the action is)
  return
end


The validation code on person, will be executed everytime you save a person. To save bypassing the validator, write @person.save(false).
Hope it integrate the pcg79's answer

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜