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

アカウント#新規

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

モデルを変更して、タイプを「メンバー」ではなく「管理者」に初期化できます。

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