1

我有两个模型:

路线和活动

我通过如下迁移在它们之间建立了多对多关系:

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>

有谁知道我能让这成为可能吗?谢谢 :)

4

1 回答 1

1

你不能这样做

ruta.activities_attributes << @activitiesarray

因为accepts_nested_attributes_for只提供了一种*_attributes=方法,所以以下应该有效

ruta.activities_attributes = @activitiesarray
于 2013-02-28T23:50:59.470 回答