2017-02-01 10 views
0

私は愚かな問題に直面しています。私は、モデルstaffとtaskとの間の関係を参照するjoinテーブル "staffs_task"に要素を作成するコレクションselectを作成しました。 そして今私は2つのことを望みます:(1)このアソシエーションを削除するボタン(2)と、私のモデルstaffs_taskのコードを少し削除して、重複を避けるようにします。そして、最後の情報は、タスクが牧場で構築されたモデルですコレクションから要素を削除する

私のコード:

(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 

何かを持っている場合この2つの事のいずれかについてのアイデアは、あなたの助けが歓迎されるでしょう 事前に感謝!!

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こと - あなたがウィザードによって運ばスティックについて話している場合を除き:

答えて

0

は、あなたが参加したモデルで、多くの設定を次のように多くを持っていると言うことができます。

ActiveRecordは、すべてのhas_many関係の "魔法の" _idsセッターを作成します。 has_many through:関係のレールを使用すると、ジョインテーブルから行を削除するだけで十分です。

あなたは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つの高価な書き込みクエリを待つ必要があります。

関連する問題