在railscast之后保存到交叉表的麻烦

时间:2012-07-14 06:13:53

标签: ruby-on-rails-3 nested-attributes attr-accessor

我试图创建嵌套属性,如此railscast中所述http://railscasts.com/episodes/167-more-on-virtual-attributes?view=asciicast

在我的示例中,我尝试将活动与图像相关联,因此我的结构为activity -> activity_image -> image

当我保存我的活动时,rails会创建活动和图像,但是我没有保存activity_image的交叉表。当然,我从来没有告诉过rails来保存这个,但是跟随我的跟踪器也没有。

是否有某种方式应该在模型中定义?我有什么问题?

class Activity > ActiveRecord::Base
    attr_accessible :title, :description, :activity_image_url

    belongs_to :user
    has_many :activity_images
    has_many :image_urls, :through => :activity_images

    #validates_presence_of :title, :description, :url

  attr_accessor :activity_image_url
  after_save :assign_image

  private
  def assign_image
      if @activity_image_url
          self.activity_image_url = ImageUrl.find_or_create_by_url(@activity_image_url)
      end
  end
end

0 个答案:

没有答案