[英]Rails How to use has_many_and_belongs_to_many with accepts_nested_attributes_for
I have two models: 我有两个模型:
Routes and Activity 路线与活动
I have a Many-To-Many relationship between them through a migration that looks like: 通过以下迁移,我之间存在多对多关系:
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
In a rest service i get the data for a route and I get multiple activities, my models look like this: 在休息服务中,我获取路线的数据,并获得多个活动,我的模型如下所示:
class Route < ActiveRecord::Base
attr_accessible :activities_attributes
has_and_belongs_to_many :activities
accepts_nested_attributes_for :activities
end
and: 和:
class Activity < ActiveRecord::Base
attr_accessible :activitytext, :iconid
has_and_belongs_to_many :routes
end
On my app controller I want to make something like : 在我的应用控制器上,我想做类似以下的事情:
ruta=Route.create({
#other data for the model
})
ruta.activities_attributes = @activitiesarray #Array made with the Activities received
But I get an error: 但是我得到一个错误:
undefined method `activities_attributes' for #<Route:0x2bccf08>
If i left it like : 如果我像这样离开它:
ruta.activities_attributes << @activitiesarray
I get: 我得到:
undefined method `with_indifferent_access' for #<Activity:0x6af7400>
Does anyone know ho can I make that possible? 有谁知道我能做到这一点吗? Thank you :)
谢谢 :)
You can't do this 你做不到
ruta.activities_attributes << @activitiesarray
because accepts_nested_attributes_for
only provides a *_attributes=
method so the following should work 因为
accepts_nested_attributes_for
仅提供*_attributes=
方法,所以以下内容应能工作
ruta.activities_attributes = @activitiesarray
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.