这可能是非常规的,但是可以扩展控制器中的任何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个模型;用户模型,船长模型,它是具有用户和团队模型的自联接模型。我正在尝试在团队模型和队长模型之间建立一对一的关系,用户可以从该团队的用户中为团队选择队长;下面是我的模特..
团队模型 class Team&lt;的ActiveRecord :: Base的 has_many:个人资料,通过:: users has_one:captain,:class_name =&gt; “用户” 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