I''m stymied at how to create a fixture that establishes a has_many
:through relationship.
I''ve watched the railscast at:
http://media.railscasts.com/videos/081_fixtures_in_rails_2.mov
... but that''s for HABTM relationships. I''ve read:
http://www.ruby-forum.com/topic/145676
but that ultimately doesn''t answer any question. So with no further
ado:
==== The models:
class User < ActiveRecord::Base
has_many :user_roles, :dependent => :destroy
has_many :roles, :through => :user_roles
end
class Role < ActiveRecord::Base
has_many :user_roles, :dependent => :destroy
has_many :users, :through => :user_roles
end
class UserRole < ActiveRecord::Base
belongs_to :role
belongs_to :user
end
==== The schema:
create_table "users", :force => true do |t|
t.string "name", :default => "",
:null => false
t.string "email", :default => "",
:null => false
end
create_table "roles", :force => true do |t|
t.string "name"
end
create_table "user_roles", :force => true do |t|
t.integer "role_id"
t.integer "user_id"
end
===
I understand that you cannot directly add roles in a user fixture, i.e.
the following does NOT work:
==== file: fixtures/roles.yml
administrator:
name: administrator
user:
name: user
guest:
name: guest
==== file: fixtures/users.yml
superuser:
name: "Superuser"
email: root-G38qTXvhaKll57MIdRCFDg@public.gmane.org
roles: administrator, user
===
... since YAML will try to directly write to the nonexistent user.roles
column. But I WOULD expect that you could write a user_roles.yaml file
to make explicit associations, along the lines of:
==== file: fixtures/roles.yml
administrator:
name: administrator
user:
name: user
guest:
name: guest
==== file: fixtures/users.yml
superuser:
name: "Superuser"
email: root-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org
==== file: fixtures/user_roles.yml
one:
user: users(:superuser)
role: roles(:administrator)
two:
user: users(:superuser)
role: roles(:user)
===
... but no combination of "roles(:user)",
"roles(:user).find",
"roles(:user).find.id" etc appears to create the correct associations.
Before Marnen tells me to put aside my Luddite tendencies and that I
should learn factory_girl or Machinist or the next testing framework du
jour, is there any sensible way to do this using fixtures?
- ff
--
Posted via http://www.ruby-forum.com/.
--
You received this message because you are subscribed to the Google Groups
"Ruby on Rails: Talk" group.
To post to this group, send email to
rubyonrails-talk-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org
To unsubscribe from this group, send email to
rubyonrails-talk+unsubscribe-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en.