[英]How do I set an attribute on the join model when using accepts_nested_attributes_for?
Is it possible to set an additional attribute on the join model
when using accepts_nested_attributes_for
? 使用
accepts_nested_attributes_for
时是否可以在accepts_nested_attributes_for
join model
上设置其他属性?
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
. 上面的方法可以工作,但是
user.roles.type
默认为member
。 At the time of registration, I need user.roles.type
to default to admin
. 在注册时,我需要
user.roles.type
默认为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.type = "member" if self.new_record?
end
end
Inheritance could solve this issue but I find it complicates things. 继承可以解决这个问题,但是我发现它使事情变得复杂。 I need roles to be dynamic so users can add their own admins and mods, and so on.
我需要角色是动态的,以便用户可以添加自己的管理员和mod,等等。 I think I'm running into these issues because I'm not modeling my data modeling correctly.
我认为我遇到了这些问题,因为我没有正确建模数据模型。
You could change your model to initialize the type to "admin" instead of "member". 您可以更改模型以将类型初始化为“ admin”而不是“ member”。
private
def init
self.type = "admin" if self.new_record?
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.