所以我想保存一个HABTM关系,但我的模型上有额外的字段,所以我使用has_many并通过方法。 这是我的模特:
#project_task.rb
class ProjectTask < ActiveRecord::Base
attr_accessible :description, :name, :user_id, :project_id, :user_ids
belongs_to :project
belongs_to :user #Created by
has_many :project_task_users #Here is the HABTM
has_many :users, :through => :project_task_users #AND HERE
validates :name, :presence => true
validates :project_task_users, :length => { :minimum => 1} #must have atleast 1 record in the HABTM relation
accepts_nested_attributes_for :project_task_users
end
#project_task_user.rb
class ProjectTaskUser < ActiveRecord::Base
belongs_to :user
belongs_to :project_task
end
我的表格:
<p>Users:</p>
<% for user in @users %>
<div>
<%= check_box_tag "project_task[user_ids][]", user.id, @task.users.include?(user) %>
<%= user.name %> - <%= user.company.name %>
</div>
<% end %>
我的控制器:
def new_task
@project = Project.find(params[:project_id])
@task = ProjectTask.new(:project_id => @project.id)
@users = @project.users
end
def new_task_post
@project = Project.find(params[:project_id])
@task = ProjectTask.new params[:project_task]
@task.user_id = current_user.id
if @task.save
redirect_to @project
else
@users = @project.users
render action:"new_task"
end
end
当我提交时,@task.save
返回false,错误数组返回project_task_users
验证
正如Pablo89指出我将check_box_tag重命名为此
<%= check_box_tag :user_ids, user.id, @task.users.include?(user), :name => 'project_task[user_ids][]' -%>
只有当我注释掉验证时它才会保存。如何在创建project_task时验证是否选择了用户?