2

对于我认为应该相当直截了当的事情,我真的很难过。希望有人可以为我提供一些启示。

我有以下具有 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 = Cavaliers)并且还有一个昵称,或者一个全新的并且有或没有昵称 - 四个可能性。

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

4

0 回答 0