2013-06-03 21 views
1

我是Rails的新手,所以我有一個新手問題。驗證不同模型的值

我們有一個表單,允許管理員設置,看起來像這樣的新用戶:

<%= form_for :user, :url => url_for(:action => 'create_user', :account_id => @account.id, :hide_form => 1), :html => {:name => 'new_user_form', :id => 'new_user_form', :remote => true} do |f| %> 
    First Name: 
    <% f.text_field 'first_name' %><br/> 
    Last Name: 
    <%= f.text_field 'last_name' %><br/> 
    Username: 
    <%= f.text_field 'login' %><br/> 
    Email: 
    <%= f.text_field 'email' %><br/> 
    Agency Code: 
    <%= text_field_tag 'agency_code', @default_agency_code %><br/> 

    <div class="button-bar"> 
    <%= f.submit :id => "submit_button" %> 
    </div> 
<% end %> 

到目前爲止,一切都很好。

def remote_create_user 
    @user = User.new(params[:user]) 
    @user.agency = Agency.find{|agency| agency.product_code == params[:agency_code]} 
    if @user.valid? and @user.save 
    # Move some stuff around for the new user 
    else 
    @error = "Failure to Save:" 
    @user.errors.full_messages.each {|msg| @error += " - #{msg}"} 
    end 
end 

我的理解是,在認爲開始<%= form_for :user行讓ERB觀點:當表單提交猛推所有的表單值成User對象,被稱爲並將其保存到數據庫中的作用知道使用User模型中指定的驗證邏輯來​​驗證所有與User類直接對應的表單域。

但是,表格中的最後一個字段(Agency Code: <%= text_field_tag 'agency_code', @default_agency_code %><br/>)與User模型中的屬性不符。相反,它對應於Agency.product_codeAgency模型定義了該屬性的驗證。我如何告訴Rails在Agency模型中使用此字段的驗證邏輯?如果沒有辦法直接做到這一點,我如何直接將驗證添加到機構代碼文本字段?

回答

1

您可以簡單地使用

@user.agency = Agency.find_by_id{|agency| agency.product_code == params[:agency_code]} 

,並在您的用戶模型,

validates :agency_id, :presence => true 

find_by_id會在這種情況下更好地工作,不是簡單地find因爲如果沒有找到該模型返回nil

+0

非常感謝您的回覆!有人認爲我有點困惑:對User模型的改變如何讓Rails知道在'Agency'模型中查找驗證? – Kevin

+1

如果我把它弄好了,看看你的代碼,似乎你選擇了一個現存的代理商,並且在創建用戶時不更新。在這種情況下,如果找到該機構,該機構將始終有效,因此實際上您想驗證用戶屬性 - 他應該有一個代理機構。代理模型沒有驗證,它在用戶上 - 它需要有一個代理(因此,agency_id不能爲空)。如果您在添加用戶後修改代理機構,則需要使用[嵌套表單](http://stackoverflow.com/q/5073698/413494) – fotanus