2013-02-28 23 views
1

使用has_many_and_belongs_to_many我有兩個型號:的Rails如何與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> 

有沒有人知道我可以做到這一點嗎? 謝謝:)

回答

1

你不能做到這一點

ruta.activities_attributes << @activitiesarray 

因爲accepts_nested_attributes_for只是提供了一個*_attributes=方法,所以下面應該工作

ruta.activities_attributes = @activitiesarray 
+0

對不起,我錯過了問題的修正,當我離開它'='我得到︰未定義的方法'activities_attributes'的#<路線:0x2bccf08> 更新了問題:) – ArcherDragon57 2013-03-01 00:27:04

+0

現在你提到它,你正在使用habtm這是不會w ork with'accepts_nested_attributes_for' – jvnill 2013-03-01 00:32:03

+0

我可以使用has_many和:through並創建一個連接表而不是遷移? – ArcherDragon57 2013-03-01 00:35:47

相關問題