【问题标题】:How do I set an attribute on the join model when using accepts_nested_attributes_for?使用 accept_nested_attributes_for 时如何在连接模型上设置属性?
【发布时间】:2012-05-01 16:01:45
【问题描述】:

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

我有用户、帐户和角色模型。 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

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

【问题讨论】:

    标签: ruby-on-rails ruby activerecord has-many has-many-through


    【解决方案1】:

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

    private
    def init
      self.type = "admin" if self.new_record?
    end
    

    【讨论】:

    • 我不想这样做,因为记录需要是“管理员”的唯一时间是在注册时。大多数其他情况会有所不同。我一直认为我的数据建模不正确。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-17
    • 1970-01-01
    • 2019-04-28
    • 1970-01-01
    • 2015-07-28
    • 1970-01-01
    相关资源
    最近更新 更多