Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I set ActiveRecord model attribute when using .build method with Rails 3.2 (many-to-many)
    text
    copied!<p>I'm working on a sort of project management app with Rails (my Rails skills is kinda rusty). I have two model objects, in this case User and Account, which have a many-to-many relationship (Company could maybe be a better name for Account). When a user signs up a new Account is created (with .build) with help form a nested form. The Account model have two fields name and account_admin. When the the initial user creates it's Account I want to set account_admin to the users id. But I can't get this to work. </p> <p>The models is set up like this:</p> <pre><code>class Account &lt; ActiveRecord::Base attr_accessible :name, :account_admin validates_presence_of :name has_many :projects, dependent: :destroy has_many :collaborators has_many :users, through: :collaborators end class User &lt; ActiveRecord::Base has_secure_password attr_accessible :email, :name, :password, :password_confirmation, :accounts_attributes has_many :collaborators has_many :accounts, through: :collaborators accepts_nested_attributes_for :accounts [...] </code></pre> <p>The UserController looks like this:</p> <pre><code>def new if signed_in? redirect_to root_path else @user = User.new # Here I'm currently trying to set the account_admin value, but it seems to be nil. account = @user.accounts.build(:account_admin =&gt; @user.id) end end </code></pre> <p>I have also tried to move <code>account = @user.accounts.build(:account_admin =&gt; @user.id)</code> to the create action, but the the field disappears from the form. </p> <p>What would be the appropriate way to accomplish what I want (set account_admin to the users id when it is getting created)? Or is there a better approach to find out which user created the account (ie. do something with the relationship table)? </p> <p><strong>Update</strong></p> <p>With help from @joelparkerhenderson I think I got it to work. I made a method in my User model that looks like this:</p> <pre><code>def set_account_admin account = self.accounts.last if account.account_admin == nil account.account_admin = self.id account.save end end </code></pre> <p>Which I call with <code>after_create :set_account_admin</code>. This works, but is there a more "Rails way" to do the same?</p> <p>Thanks. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload