开发者

Trouble on saving an associated model and then retrieve some data from that

开发者 https://www.devze.com 2023-02-18 22:58 出处:网络
I am using Ruby on Rails 3 and I am trying to retrieve some data from a just saved child model (associated model) in order to store that data in the parent model.

I am using Ruby on Rails 3 and I am trying to retrieve some data from a just saved child model (associated model) in order to store that data in the parent model.

More precisely (in steps) I would like to do:

  1. Save the child model Account of the parent model User
  2. Retrieve the just created Account ID value and save that value in the User model attribute named users_account_id.

... and more explicitly (in values) I would like to have the following scenario after saving the child model Account:

# Account values
Account.id = 222
Account.name = "Test_name"
...
Account.user_id = 111

# User values
User.id = 111
User.users_account_id = 222

I already implemented the first step, but how can I implement the second step?


In order to retrieve the Account ID, I tryed to use an association callback

class User < ActiveRecord::Base
  has开发者_运维知识库_one :account, :before_add => :callback_name


  validates_associated :account
  accepts_nested_attributes_for :account

  def callback_name
    self.users_account_id = Account.find_by_id(self.id).id
  end
end

but I get this error:

Unknown key(s): before_add


This is way overkill. All you need to do is put the user_id in the form of the account that is getting created as a hidden field.

<% form_for(@account) do |f| %>
    <%= f.hidden_field :user_id, :value => current_user.id %>
<% end %>

Of course add your other fields that you want for account and you need a current_user object which you will need anyways with your current logic.


I'm going to side step your question a bit, and ask why you need IDs pointing in both directions? I assume you want your User to be related to an Account, and an Account to have one or more Users. The "Rails Way" to do this would be something like the following:

class User < ActiveRecord::Base
    belongs_to :account
end

class Account < ActiveRecord::Base
    has_many :users
end

In your database the users table will have account_id and the accounts table will not have a user_id of any kind.

This will still allow you to user the association in both directions:

some_user.account # Returns the correct account object
some_account.users # Returns all users for the account

I hope this helps somewhat!

0

精彩评论

暂无评论...
验证码 换一张
取 消