1

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 :)

1 Answer 1

1

You can't do this

ruta.activities_attributes << @activitiesarray

because accepts_nested_attributes_for only provides a *_attributes= method so the following should work

ruta.activities_attributes = @activitiesarray
Sign up to request clarification or add additional context in comments.

4 Comments

Sorry, I missed a correction on the question, when I left it with '=' I get: undefined method `activities_attributes' for #<Route:0x2bccf08> Updated the question :)
now that you mentioned it, you are using habtm which is not going to work with accepts_nested_attributes_for
Could I use has_many and :through and create a join table instead of a migration?
yes, you should use has_many through when you are going to add more details in the join table. you should also use a migration to create the join table.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.