在has_many中保存连接模型属性时遇到问题:通过rails中的关联

时间:2012-11-19 06:54:21

标签: ruby-on-rails nested-attributes has-many-through

我认为应该相当直接的事情真的很难。希望那里有人可以为我提供一些启示。

我有以下带有has_many:through关系的模型。

class School < ActiveRecord::Base
  attr_accessible :name

  has_many :school_mascots, :dependent => :destroy
  accepts_nested_attributes_for :school_mascots

  has_many :mascots, :through => :school_mascots
end

class Mascot < ActiveRecord::Base
  attr_accessible :name

  has_many :school_mascots, :dependent => :destroy
  has_many :schools, :through => :school_mascots
end

class SchoolMascot < ActiveRecord::Base
  # yes, it has a primary key (:id)

  attr_accessible :school_id
  belongs_to :school

  attr_accessible :mascot_id
  belongs_to :mascot
  accepts_nested_attributes_for :mascot

  attr_accessible :nickname # this is an additional attribute on the join model
end

我正在尝试用适当的吉祥物协会创建学校记录。我的学校控制器看起来像......

class SchoolsController < ApplicationController
  respond_to :json

  def index
    @schools = School.all
  end

  def show
    @school = School.find_by_id(params[:id])
  end

  def create
    @school = School.new(params[:school].except("mascots"))

    # add the mascot(s) to the new school; theoretically there could be more than one
    params[:school][:mascots].each do |mascot|
      # :id will be present if the mascot exists and can be reused
      # :nickname will be present if there is a nickname for the mascot
      # if :id is present, don't overwrite the mascot's data; although the nickname can be new since the join record is unique

      mascot_to_associate = {:mascot => Mascot.find_or_initialize_by_id(mascot[:id], mascot.except("nickname"))}

      if mascot[:nickname]
        mascot_to_associate.merge!(:nickname => mascot[:nickname])
      end

      @school.school_mascots.build_mascot(mascot_to_associate)
    end

    @school.save

    respond_with @school
  end
end

我的请求的结构类似于以下json(此示例包含所有可能的输入)...

{"school":{"name":"Univerisity of Virginia","mascots":[{"id":"1"},{"id":"2","nickname":"Old Dominion"},{"name":"Hoos"},{"name":"Wah-hoo-wah","nickame":"Hoos"}]}}

所以,吉祥物可以是一个可以重复使用的(1 = Wahoos)而没有昵称,一个可以重复使用(2 =骑士)并且还有一个昵称,或者是一个全新的,或者有一个昵称的吉祥物 - 四种可能性。

我已经能够将学校和吉祥物联系起来,但是一旦我在联盟表上引入昵称栏,它就会走下坡路。我已经尝试了各种组合来保存关联,但我似乎无法让它工作。以上是我最近的尝试。但是你说它并且我已经尝试过了。我只是需要一些帮助。我哪里错了?谢谢!

0 个答案:

没有答案