HXH
HXH

Reputation: 1663

Rails add record based on many-to-many association

I have 3 model,and their relation is many-to-many

MMem:

class MMem < ActiveRecord::Base
   has_many :t_mem_task_records
   has_many :m_tasks,through: :t_mem_task_records
end

TMemTaskRecord:

class TMemTaskRecord < ActiveRecord::Base
  belongs_to :m_mem
  belongs_to :m_task
end

TMemTask:

class TMemTask < ActiveRecord::Base 
   has_many :t_mem_task_records
   has_many :m_mems,through: :t_mem_task_records
end

If I want to get all TMemTasks of specified MMem,I can write:

MMem.find(1).m_tasks

Now,I want to add a TMemTask to specified MMem

MMem.find(1).m_tasks.create(MTask.find(1))

But I got an error:

NoMethodError: undefined method `stringify_keys' for #<MTask:0xb822624>

Why I got this error? or any other solution?

Upvotes: 0

Views: 32

Answers (1)

xdazz
xdazz

Reputation: 160963

.create is used to create a new MTask, if you want to add an existed MTask to the association, then use:

MMem.find(1).m_tasks << MTask.find(1)

Upvotes: 1

Related Questions