Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent for write_attribute for associations in Rails?

I'd like to override the setter for an association, but write_attribute() isn't working - probably because that method only works for database columns.

I have tried super(), but that doesn't work either (didn't think it would... but it was worth a guess).

How do I override the setter? Here is what I am trying to do:

  def parent=(value)
    # this line needs to be changed
    write_attribute(:parent, value)

    if value.subject.start_with?('Re:')
      self.subject = "#{value.subject}"
    else
      self.subject = "Re: #{value.subject}"
    end

    self.receivers << value.sender
  end
like image 482
Fire Emblem Avatar asked May 28 '11 15:05

Fire Emblem


3 Answers

What worked for me is the following:

def parent=(new_parent)
  # do stuff before setting the new parent...

  association(:parent).writer(new_parent)
end
like image 79
Lefteris Laskaridis Avatar answered Sep 23 '22 09:09

Lefteris Laskaridis


I found one way to do it, but I am disturbed by it:

  alias_method :old_parent=, :parent=

  def parent=(value)
    self.old_parent = value

    if value.subject.start_with?('Re:')
      self.subject = "#{value.subject}"
    else
      self.subject = "Re: #{value.subject}"
    end

    self.receivers << value.sender
  end

One thing I don't necessarily like about Rails is that whenever you want to do something that is out of the norm just a bit - but not unreasonable by any means - the "how" is very different than what your intuition would come up with.

It's not a problem when you know the exceptions, but when you're learning, this sort of irregularity and inconsistency on how to do things makes it harder to learn - not easier.

Java might be initially harder to learn, but it's way more consistent. Your intuition can take you a lot further once you think in Java. This is not true once you think in Rails. Rails is about memorization of methods to call and memorization on how to do things. In java, you can reason it out a lot more... and intellisense fills in the rest.

I'm just disappointed. This is a reoccurring pattern for me - I want do something that is just "a little more complex" than the framework examples... and the "how" is inconsistent and takes 30 minutes or maybe even hours to locate and find the answer for it.

like image 34
Fire Emblem Avatar answered Sep 25 '22 09:09

Fire Emblem


In Rails 4.2.1 doc:

# Association methods are generated in a module that is included into the model class,
# which allows you to easily override with your own methods and call the original
# generated method with +super+. For example:
#
#   class Car < ActiveRecord::Base
#     belongs_to :owner
#     belongs_to :old_owner
#     def owner=(new_owner)
#       self.old_owner = self.owner
#       super
#     end
#   end
like image 32
muichkine Avatar answered Sep 23 '22 09:09

muichkine