class Party < ActiveRecord::Base
belongs_to :hostess, class_name: 'Person', foreign_key: 'hostess_id'
validates_presence_of :hostess
end
class Person < ActiveRecord::Base
has_many :parties, foreign_key: :hostess_id
end
當在創建新Party
,視圖允許用戶選擇現有Hostess
,或者輸入一個新的。 (這是通過jQuery自動完成來查找現有記錄完成的。)如果選擇了現有記錄,則params[:party][:hostess_id]
將具有正確的值。否則,params[:party][:hostess_id]
是0
和params[:party][:hostess]
具有創建新的Hostess
(例如,params[:party][:hostess][:first_name]
等)保存belongs_to的數據創建新的記錄
在Parties
控制器的數據:
def create
if params[:party][:hostess_id] == 0
# create new hostess record
if @hostess = Person.create!(params[:party][:hostess])
params[:party][:hostess_id] = @hostess.id
end
end
@party = Party.new(params[:party])
if @party.save
redirect_to @party, :notice => "Successfully created party."
else
@hostess = @party.build_hostess(params[:party][:hostess])
render :action => 'new'
end
end
這當我通過在現有Hostess
工作正常,但在嘗試創建新的Hostess
(無法創建新的Hostess/Person
,因此無法創建新的Party
)時它不起作用。有什麼建議麼?
非常感謝您提供瞭如此全面的答案。只有'def set_selected_hostess'需要使用Person模型,例如'self.hostess = Person.find(hostess_id)'。我在模型中也有attr_accessible,我註釋了。無論如何不需要(由發電機添加)。 – Brenda
你搖滾!非常感謝你!!!但是我在Rails 4中遇到了問題。我有:一個人有很多票。在票據表格中,我需要填寫個人屬性。當我執行@ticket = Ticket.new(ticket_params)時,我得到ID = 1的票未找到ID = 1的票,ID = – fabricioflores