Note that there are some explanatory texts on larger screens.

plurals
  1. POUse virtual attribute in nested model before_save callback
    primarykey
    data
    text
    <p>I have a User model and a Tracker model. User has_many Trackers and Tracker belongs_to User. The User model has a virtual attribute called tracker_date that I would like to be able to use in a before_save callback in the Tracker model. The callback is supposed to set the date in the Tracker model for all of the Tracker records updated at the same time through the nested attributes association. Is this possible? Or is there a better way to do what I am trying to do? </p> <p>The view: </p> <pre><code>&lt;%= form_for @user, :url =&gt; {:controller =&gt; 'trackers'}, :method =&gt; 'post' do |f| %&gt; &lt;%= f.label :tracker_date, "Week ending" %&gt; &lt;%= f.text_field :tracker_date %&gt; &lt;br /&gt; &lt;% @user.top_items.each do |item| %&gt; &lt;%= f.fields_for :trackers, item.trackers.build do |g| %&gt; &lt;%= item.top_item_name %&gt; &lt;%= g.text_field :value %&gt; &lt;%= g.hidden_field :position_id, :value =&gt; item.id %&gt; &lt;br /&gt; &lt;% end %&gt; &lt;% end %&gt; &lt;%= f.submit "Submit" %&gt; &lt;% end %&gt; </code></pre> <p>User.rb</p> <pre><code>has_many :trackers accepts_nested_attributes_for :trackers attr_accessor :tracker_date attr_accessible :tracker_date, :trackers_attributes </code></pre> <p>Tracker.rb</p> <pre><code>belongs_to :user attr_accessible :date before_save :set_date def set_date self.date = self.user.tracker_date end </code></pre> <p>In this example, the date does not get set in the Tracker model with the value in the virtual attribute from the User model. I also tried a simple validation in the Tracker model using the virtual attribute from the User model but that did not work either. Is there a way to get it to work or is there a better way to do this that either avoids using the virtual attribute or allows the nested model to access the virtual attribute?</p> <p>Thanks. </p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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