[英]Trying to use accepts_nested_attributes_for and has_and_belongs_to_many but the join table is not being populated
[英]Rails How to use has_many_and_belongs_to_many with accepts_nested_attributes_for
我有两个模型:
路线与活动
通过以下迁移,我之间存在多对多关系:
class ActivitiesRoutes < ActiveRecord::Migration
def up
create_table :activities_routes, :id => false do |t|
t.integer :route_id
t.integer :activity_id
end
end
end
在休息服务中,我获取路线的数据,并获得多个活动,我的模型如下所示:
class Route < ActiveRecord::Base
attr_accessible :activities_attributes
has_and_belongs_to_many :activities
accepts_nested_attributes_for :activities
end
和:
class Activity < ActiveRecord::Base
attr_accessible :activitytext, :iconid
has_and_belongs_to_many :routes
end
在我的应用控制器上,我想做类似以下的事情:
ruta=Route.create({
#other data for the model
})
ruta.activities_attributes = @activitiesarray #Array made with the Activities received
但是我得到一个错误:
undefined method `activities_attributes' for #<Route:0x2bccf08>
如果我像这样离开它:
ruta.activities_attributes << @activitiesarray
我得到:
undefined method `with_indifferent_access' for #<Activity:0x6af7400>
有谁知道我能做到这一点吗? 谢谢 :)
你做不到
ruta.activities_attributes << @activitiesarray
因为accepts_nested_attributes_for
仅提供*_attributes=
方法,所以以下内容应能工作
ruta.activities_attributes = @activitiesarray
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.