Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Html 从集合中删除元素_Html_Ruby On Rails_Ruby - Fatal编程技术网

Html 从集合中删除元素

Html 从集合中删除元素,html,ruby-on-rails,ruby,Html,Ruby On Rails,Ruby,我正面临一个愚蠢的问题。我已经创建了一个集合select,它正在将元素创建到联接表“staff_task”中,以引用模型staff和task之间的关联。 现在我想要两件事:(1)一个按钮删除这个关联(2)和我的模型staff_任务的一点代码,以避免重复,所以有了task_id和staff_id。最后一个信息,task是ranch建立的模型 我的代码: (新任务中的集合) true%> (任务控制器) 操作前跳过:配置注册参数 行动前:设置牧场 操作前:设置任务,除了:[:创建] def创建 @

我正面临一个愚蠢的问题。我已经创建了一个集合select,它正在将元素创建到联接表“staff_task”中,以引用模型staff和task之间的关联。 现在我想要两件事:(1)一个按钮删除这个关联(2)和我的模型staff_任务的一点代码,以避免重复,所以有了task_id和staff_id。最后一个信息,task是ranch建立的模型

我的代码:

(新任务中的集合)

true%>
(任务控制器)

操作前跳过:配置注册参数
行动前:设置牧场
操作前:设置任务,除了:[:创建]
def创建
@task=@ranch.tasks.create(任务参数)
@Staff=Staff.where(:id=>params[:Staff\u task])

@task.staff假设您有以下多对多的连接模型设置:

class Staff
  has_many :assignments
  has_many :tasks, through: :assignments
end

class Task
  has_many :assignments
  has_many :staff, through: :assignments
end

class Assignment
  belongs_to :task
  belongs_to :staff
end
请注意-除非你说的是巫师携带的棍子

ActiveRecord为所有具有许多关系的
创建“神奇的”
\u ID
设置器。当与
has\u many through:
关系一起使用时,rails足够智能,只需从联接表中删除行即可

您可以将其与collection_复选框方法一起使用:

<%= form_for([@task.ranch, @task]) do |f| %>
  <%= f.collection_select(:staff_ids, Staff.all, :id, :name, multiple: true) %>
<% end %>
staff\u id:[]
将允许一个标量值数组。也不是说
。新建
创建
不是一回事!如果记录有效,您可以将其保存4次,这样用户就必须等待4次昂贵的写入查询

class Staff
  has_many :assignments
  has_many :tasks, through: :assignments
end

class Task
  has_many :assignments
  has_many :staff, through: :assignments
end

class Assignment
  belongs_to :task
  belongs_to :staff
end
<%= form_for([@task.ranch, @task]) do |f| %>
  <%= f.collection_select(:staff_ids, Staff.all, :id, :name, multiple: true) %>
<% end %>
def create 
  @task = @ranch.tasks.new(task_params) do |t|
    # this should really be done by setting default values
    # for the DB columns
    t.done = false
    t.star = false
  end

  if @task.save
    redirect_to @ranch, success:  "The task was created"
  else 
    render :new, error: "The task was not created"
  end
end 

private

def task_params
  params.require(:task)
    .permit(:content, :deadline, :row_order, :date, :assigned_to, staff_ids: [])
end