[英]validating nested model when user selects foreign key value - rails
我有一個嵌套模型Task屬於Project,因此在我的模型中:
class Task < ActiveRecord::Base
belongs_to :project
validates :project_id, :presence => true
在我的項目模型中,我有:
class Project < ActiveRecord::Base
has_many :tasks, :dependent => :destroy
現在,我有了一個用於創建新任務的表單,用戶可以在其中指定project_id,即任務所屬的項目。 所以我的表單看起來像這樣:
<%= form_for [@project, @task], :remote => true do |f| %>
<%= f.label :title, "Title" %>
<%= f.text_field :title %>
<%= label_tag("Project") %>
<%= select(nil, :project_id, (get_active_projects).collect {|p| [p.title, p.id] }, {:prompt => 'Select Project'}) %>
<%= f.label :description %>
<%= f.text_area :description %>
<div class="actions">
<%= f.submit 'Save' %>
</div>
<% end %>
驗證存在的問題是,如果用戶未在表單中選擇項目(project_id),則會收到一條錯誤消息,提示無法在完成驗證之前找到項目? 我希望在嘗試找到項目之前進行驗證,以強制存在project_id。
def create
@project = Project.find(params[:project_id])
@task = @project.tasks.new(params[:task])
@task.update_attributes(:status_id => 2)
@task.save!
用您的方式嘗試在方法中查找項目,如果project_id為nil,則會出現該錯誤。 由於具有has_many和belongs_to關系,因此足以將project_id保存在Task中,而您不必通過項目創建任務。 當您創建任務時,在form_for中不需要很多項目對象,因為您可以像這樣去
<%= form_for @task, :remote => true do |f| %>
<%= error_messages_for(@task) %>
<%= f.label :title, "Title" %>
<%= f.text_field :title %>
<%= f.label :project_id %>
<%= f.select(nil, :project_id, (get_active_projects).collect {|p| [p.title, p.id] }, {:prompt => 'Select Project'}) %> (just check the select syntax if i did something wrong)
<%= f.label :description %>
<%= f.text_area :description %>
<div class="actions">
<%= f.submit 'Save' %>
</div>
<% end %>
那么在您的控制器方法中應該像這樣簡單
def create
params[:task][:status_id] = 2
@task = Task.new(params[:task])
if @task.save!
what you want to do if valid
else
go back to same page with errors
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.