Colin, I figured out most of it. But stayed stuck on a detail.
My app now has Account, User, and Role models. The Role model links the
Account and User models. User has_many roles, and has_many accounts
through
roles. User accepts_nested_properties for accounts.
Everything works except for setting an extra attribute on the Role
model.
The Role model has a role_type column that I want to set when the
records
are created. It keeps showing up blank though.
Basically, when the User and the Account objects are created, I want the
Role model that joins them to have “owner” in the role_type column. But
it’s showing up blank. I feel like I am mixing up “ownership” with
“roles”,
yet it seems natural to store the in the same table. I thought I could
use
inheritance to simplify it, but it’s causing more headaches. I can’t
change
the type column arbitrarily if I wanted to change the role of a use for
example.
My questions are: How do I set the role_type column? And is it stupid?
It
doesn’t seem like a good way to set up something meant to be secure in
such
a way.
Should I use inheritance instead and create separate associations for
each
role type?
Models:
class User < ActiveRecord::Base
attr_accessible :name, :email, :password, :password_confirmation,
:accounts, :accounts_attributes
has_many :roles
has_many :accounts, through: :roles
accepts_nested_attributes_for :accounts
end
class Account < ActiveRecord::Base
attr_accessible :title
has_many :roles
has_many :users, through: “roles”
end
class Role < ActiveRecord::Base
attr_accessible :account_id, :user_id, :role_type
belongs_to :account
belongs_to :user
end
Controller:
def new
@user = User.new
@role = @user.roles.build(role_type: “owner”)
@account = @user.accounts.build
end
def create
@user = User.new(params[:user])
if @user.save
redirect_to root_path
else
render ‘new’
end
end
View
<%= simple_form_for @user do |f| %>
<%= f.simple_fields_for :accounts do |account_form| %>
<%= account_form.input :title %>
<% end %>
<%= f.input :name %>
[snip]
<%= f.submit ‘Sign up’, class: ‘btn btn-primary’ %>
<% end %>