0

I'm using Ruby 2.1.5 and Rails 4.2.1 I'm trying to put some static database entries into a sqlite3 table via seeds.rb. When I run rake db:seed, I get the correct number of rows inserted with appropriate timestamp columns, but the actual data column, name, is not being populated. Name is being printed out inside the loop.

db/seed.rb

for g in ['Harmony', 'Melody', 'Technique', 'Soloing']
    Group.create(name: g)
    put(g)
end

app/models/group.rb:

class Group < ActiveRecord::Base
    attr_accessor :name
    has_many :group2exercise
    has_many :exercises, through :group2exercise
end

sqlite3 (copying the create from SQLDB Browser)

CREATE TABLE "groups"("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "name" varchar, "created_at" datetime NOT NULL, "updated_at" datetime NOT NULL)
P.H.
  • 471
  • 1
  • 4
  • 23

1 Answers1

2

It should work if you remove the line

attr_accessor :name

By having attr_accessor, a new set of getter and setter methods are created, in this case overriding what Rails provided.

roob
  • 1,116
  • 7
  • 11
  • I've found a work around but I will go back and try the proposed solutions. I *think* the problem was in the has_many statements. I went back and setup the models using "rails g scaffold groups name:string", "rails g scaffold group2exercise group:integer exercise:integer" and I did not edit the model. – P.H. Dec 08 '15 at 02:23
  • There is something quite wrong with your 'rails g' statements. If you suspect the has_many is the cause, remove it and try again. – roob Dec 08 '15 at 02:38
  • Of course I deleted the bad project without thinking once I had the original problem solved. Working backwards from my now working project I believe you are right. Both the attr_accessor and the has_many, through statements cause it to break. The other has_many is ok, although it may not be complete. – P.H. Dec 08 '15 at 13:28
  • More fundamentally, I used http://guides.rubyonrails.org/association_basics.html which is a great resource for the different types of association. My only complaint would be that the Ruby Cookbook gives firmer advice that if you are using has_one, you probably should merge your tables. Still, this page does not provide the necessary context for a new person to understand which scaffolding commands to use, whether you need to put statements into migrate scripts to enforce the foreign key relationships, etc. – P.H. Dec 08 '15 at 13:32
  • If you know of a simple tutorial or demo project that shows how to setup a many to many relationship, I would be grateful. – P.H. Dec 08 '15 at 13:32
  • Using http://www.xyzpub.com/en/ruby-on-rails/3.2/ar-many_to_many.html, I have been able to add the has_many statements. – P.H. Dec 08 '15 at 13:49
  • @P.H. Here is a very old [railscasts](http://railscasts.com/episodes/47-two-many-to-many) and an [explanation](http://stackoverflow.com/questions/7322230/correct-implementation-of-many-to-many-in-ruby-on-rails) – roob Dec 10 '15 at 10:32