0

I'm currently working on a small project using Ruby On Rails 3.2 to create a database that contains several unique Models. Each Model has many Elements and each Element has the potential to belong to many Models. I have been able to set up the models in the following manner:

class Model < ActiveRecord::Base
  has_many :model_elements
  has_many :elements, :through => :model_elements
  attr_accessible :elements, :name, :notes, :ref
end

class Element < ActiveRecord::Base
  has_many :model_elements
  has_many :models, :through => :model_elements
  attr_accessible :elementType, :name, :notes, :ref
  validates_presence_of :name
end

class ModelElement < ActiveRecord::Base
  belongs_to :Model
  belongs_to :element
  attr_accessible :model_id, :created_at, :element_id
end

My question is how do I add multiple Elements to a single Model? I've tried to find some documentation but I can't find anything. Currently I'm trying to do the following:

@model.elements = @element

Where @element is a predefined element however it's throwing the following error:

undefined method `each' for #<Element:0x007ff803066500>

Any help would be greatly appreciated.

3 Answers 3

2

Try @model.elements << @element

Sign up to request clarification or add additional context in comments.

Comments

0
collection.create(attributes = {})

Returns a new object of the collection type that has been instantiated with attributes, linked to this object through the join table, and that has already been saved.

 @model.elements.create(:name => "example")

Comments

0

Amar's answer is correct. If you wanted you can simplify your models further by using the has_and_belongs_to_many association.

class Model < ActiveRecord::Base
  has_and_belongs_to_many :elements, :join_table => :model_elements
end

class Element < ActiveRecord::Base
  has_and_belongs_to_many :models, :join_table => :model_elements
end

@model.elements << @element

Comments

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.