0

join model是否可以在使用时设置附加属性accepts_nested_attributes_for

我有用户、帐户和角色模型。Account 模型接受用户的嵌套属性。这样用户可以同时创建他们的帐户和用户记录。

class AccountsController < ApplicationController
  def new
    @account = Account.new
    @user = @account.users.build
  end
end

以上将起作用,但user.roles.type默认为member. 在注册时,我需要user.roles.type默认为admin. 这不起作用:

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

帐户#new

<%= 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

继承可以解决这个问题,但我发现它使事情变得复杂。我需要角色是动态的,以便用户可以添加自己的管理员和模组,等等。我认为我遇到了这些问题,因为我没有正确地建模我的数据建模。

4

1 回答 1

0

您可以更改模型以将类型初始化为“admin”而不是“member”。

private
def init
  self.type = "admin" if self.new_record?
end
于 2012-05-01T19:27:05.717 回答