使用accepts_nested_attributes_for创建连接模型记录

时间:2014-04-11 10:26:24

标签: ruby-on-rails nested-attributes has-and-belongs-to-many

我有以下模特

class User < ActiveRecord::Base
   has_many :project_users, dependent: :destroy
   has_many :projects, through: :project_users
end

class ProjectUser < ActiveRecord::Base
   belongs_to :user
   belongs_to :project
   has_many :participants
   has_many :tasks, through: :participants
end

class Task < ActiveRecord::Base
   belongs_to :project
   has_many :participants
   has_many :project_users, through: :participants
   accepts_nested_attributes_for :participants
end

class Participant < ActiveRecord::Base
   belongs_to :project_user
   belongs_to :task
 end

所以流程应该是这样的: 1.用户创建项目 2.用户通过连接模型ProjectUser将用户添加到项目中 3.用户为项目创建任务,并从将参与任务的ProjectUsers中选择那些用户。所以我放了一个accepts_nested_attributes_for方法并尝试构建嵌套表单。

在我的控制器中:

 def new
    @task = Task.new
    @task.participants.build
 end

 def task_params
    params.require(:task).permit(:project_id, :project_phase_id, :priority_id, :title,     :due_date, :estimation, :responsible_id, :description, :participant_ids => [])#, :participants_attributes => [:project_user_id, :task_id])
 end

participant_attributes被评论

在我看来:

= f.association :participants, as: :select

生成的实际HTML:

 <input name="task[participant_ids][]" type="hidden" value="">
 <select class="select optional form-control" id="task_participant_ids" multiple="multiple" name="task[participant_ids][]">
   <option value="57">AlexandeR MazeiN</option>
   <option value="59">Firenze</option>
   <option value="58">Vasily Strekotkin</option>
 </select>

我通过ajax,value = ProjectUser.id添加选项 我必须这样做,因为我不知道除非选择了任务的具体项目,否则将会有哪些ProjectUsers。

我收到错误:

Started POST "/tasks" for 127.0.0.1 at 2014-04-11 13:18:24 +0300
  User Load (0.7ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 6 ORDER BY "users"."id" ASC LIMIT 1
Processing by TasksController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"aXuk9ZuDvFZce+sbIQLRhWZlVjitMvySaJ7CwWfdmaQ=", "task"=>{"project_id"=>"20", "priority_id"=>"4", "project_phase_id"=>"40", "title"=>"Skepta", "due_date"=>"", "estimation"=>"8", "responsible_id"=>"6", "participant_ids"=>["", "57", "58"], "description"=>""}, "commit"=>"Create Task"}
  Team Load (0.4ms)  SELECT "teams".* FROM "teams" WHERE "teams"."id" = $1 LIMIT 1  [["id", 3]]
  Participant Load (0.5ms)  SELECT "participants".* FROM "participants" WHERE "participants"."id" IN (57, 58)
Completed 404 Not Found in 7ms

ActiveRecord::RecordNotFound - Couldn't find all Participants with IDs (57, 58) (found 0 results, but was looking for 2): 

1 个答案:

答案 0 :(得分:0)

您的param哈希的ProjectUser ID为participant_ids,因此在查询数据库时,它会查找包含这些ID的Participant个模型。您需要在参与者列表中将这些设置为project_user_id,如下所示:

participants: [ { project_user_id: 57 }, { project_user_id: 58 } ]

我对build并不是很熟悉,但是这些内容应该允许AR正确构建关联。