从集合中删除元素

时间:2017-02-01 00:25:15

标签: html ruby-on-rails ruby

我面临着一个愚蠢的问题。我创建了一个集合选择,它将元素创建到连接表“staffs_task”中,以引用模型人员和任务之间的关联。 现在我想要两件事:(1)一个按钮删除这个关联(2)和我的模型staffs_task的一些代码以避免重复,所以使用task_id和staff_id。最后一个信息,任务是由牧场建造的模型

我的代码:

(new_task中的集合)

<%= select_tag "staffs_task", options_from_collection_for_select(@staffs, 'id', 'name') , :multiple => true %> 

(task_controller)

  skip_before_action :configure_sign_up_params
  before_action :set_ranch
  before_action :set_task, except: [:create]



  def create 
    @task = @ranch.tasks.create(task_params)
    @staffs = Staff.where(:id => params[:staffs_task])
    @task.staffs << @staffs
    if @task.save
      @task.update(done: false)
      @task.update(star: false)
      flash[:success] = "The task was created "
    else 
      flash[:success] = "The task was not created "
    end
    redirect_to @ranch
  end 


private

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

  def set_ranch 
    @ranch = Ranch.find(params[:ranch_id])
  end 

  def set_task 
    @task = @ranch.tasks.find(params[:id])
  end 

因此,如果您对这两件事中的任何一件有任何疑问,那么欢迎您的帮助 在此先感谢!!

1 个答案:

答案 0 :(得分:0)

假设您使用连接模型进行了以下多对多设置:

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

请注意plural of staff is staff - 除非你在谈论巫师携带的棍棒。

ActiveRecord创造了#34;魔法&#34;所有_ids关系的has_many制定者。当与has_many through:关系一起使用时,rails足够聪明,可以从连接表中删除行。

您可以将其与collection_select和collection_checkboxes方法一起使用:

<%= 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

staff_ids: []将允许一组标量值。也不是.new.create不是一回事!如果它有效,你可以将记录保存4次,这样用户就可以等待4次昂贵的写入查询。

相关问题