I have User, Account, and Role models. The Account model accepts nested properties for users. This way users can create their account and user records at the same time.
class AccountsController < ApplicationController
def new
@account = Account.new
@user = @account.users.build
end
end
The above will work, but the user.roles.type
defaults to member
. At the time of registration, I needuser.roles.type
to default to admin
. This does not work:
class AccountsController < ApplicationController
def new
@account = Account.new
@role = @account.role.build
# Role.type is protected; assign manually
@role.type = "admin"
@user = @account.users.build
end
end
<%= simple_form_for(@account, html: { class: 'form-horizontal' }) do |f| %>
<legend>Account Details</legend>
<%= render 'account_fields', f: f %>
<%= f.simple_fields_for :users do |user_form| %>
<legend>Personal Details</legend>
<%= render 'users/user_fields', f: user_form %>
<% end %>
<%= f.submit t('views.accounts.post.create'), class: 'btn btn-large btn-primary' %>
<% end %>
class User < ActiveRecord::Base
has_many :roles
has_many :accounts, through: :roles
end
class Account < ActiveRecord::Base
has_many :roles
has_many :users, through: :roles
accepts_nested_attributes_for :users
end
# user_id, account_id, type [admin|moderator|member]
class Role < ActiveRecord::Base
belongs_to :user
belongs_to :account
after_initialize :init
ROLES = %w[owner admin moderator member]
private
def init
self.role = "member" if self.new_record?
end
end
join model
when usingaccepts_nested_attributes_for
? On 1 May 2012 22:53, Mohamad El-Husseini <hussei...@gmail.com> wrote:
>> It depends what you mean by 'work'. It will assign the type of @role
>> to "admin" but the problem is that you have not saved it to the
>> database after changing the type.
You have not responded to the point above
def new
@account = Account.new(params[:account])
@user = @account.users.build
end
def new
@account = Account.new(params[:account])
@account.save
end
current_user.accounts.build
with current_user.accounts.create
and Rails will save the Role record)def new
@account = current_user.accounts.build
end
def create
@account = current_user.accounts.build(params[:account])
@account.save
end
> To post to this group, send email to rubyonrails-talk@googlegroups.com.
> To unsubscribe from this group, send email to
> rubyonrails-talk+unsubscribe@googlegroups.com.