这可能是非常规的,但是可以扩展控制器中的任何has_one方法,例如 association=(associate) . 我已经在模型中看到了这一点,但如果可以,它可以在控制器中完成,怎么做?

关于我在驾驶什么的一些解释......

来自http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

Overriding generated methods

关联方法是在包含在模型类中的模块中生成的,这允许您使用自己的方法轻松覆盖并使用super调用原始生成的方法 . 例如:

class Car < ActiveRecord::Base
 belongs_to :owner
 belongs_to :old_owner
 def owner=(new_owner)
   self.old_owner = self.owner
   super
  end
end

也,

Association extensions

控制对关联的访问的代理对象可以通过匿名模块进行扩展 . 这对于添加仅作为此关联的一部分使用的新查找程序,创建程序和其他工厂类型方法特别有用 .

class Account < ActiveRecord::Base
     has_many :people do
       def find_or_create_by_name(name)
         first_name, last_name = name.split(" ", 2)
         find_or_create_by(first_name: first_name, last_name: last_name)
       end
     end
    end

person = Account.first.people.find_or_create_by_name("David Heinemeier Hansson")
person.first_name # => "David"
person.last_name  # => "Heinemeier Hansson"

编辑

我有3个模型;用户模型,船长模型,它是具有用户和团队模型的自联接模型 . 我正在尝试在团队模型和队长模型之间 Build 一对一的关系,用户可以从该团队的用户中为团队选择队长;下面是我的模特..

Team Model类Team <ActiveRecord :: Base has_many:profiles,通过:: users has_one:captain,:class_name =>“User”has_one:result,as :: result_table

attr_accessible :teamname, :color, :result_attributes

  after_create :build_result_table
  after_create :build_default_captain

   accepts_nested_attributes_for :profiles
   accepts_nested_attributes_for :captain
   accepts_nested_attributes_for :result

  def build_result_table
    Result.create(result_table_id: self.id, result_table_type: self.class.name)
  end

  def build_default_captain
    captain.create(team_id: self.id)
  end

end

用户模型

class User < ActiveRecord::Base
  has_one :profile
  has_many :teammates, :class_name => "User", :foreign_key => "captain_id"
  belongs_to :captain, :class_name => "User"

  # before_create :build_profile
  after_create :build_default_profile

  accepts_nested_attributes_for :profile
  attr_accessible :email, :password, :password_confirmation, :profile_attributes

  def build_default_profile
    Profile.create(user_id: self.id)
  end

结束

团队控制员

class TeamsController < ApplicationController

def new
  @team = Team.new
end 

def create
  @team = Team.new(params[:team])
  if @team.save!
   flash[:success] = "Team created."
   redirect_to @team
  else
   flash[:error_messages]
   render 'new'
  end
 end

def index
 @teams = Team.paginate(page: params[:page])
end

def show
 @team = Team.find(params[:id])
end

def edit
 @team = Team.find(params[:id])
end

def update
  @team = Team.find(params[:id])
  if @team.update_attributes(params[:team])
   flash[:success] = "Team Updated"
   redirect_to @team
  else
   render 'edit'
  end
 end

def destroy
  Team.find(params[:id]).destroy
  flash[:success] = "Team is deleted."
  redirect_to teams_url
 end


 private

  def team_params
    params.require(:team).permit(:teamname, :color)
  end

end