我有三个模型,并且有一个has_many :through
关联:
class User < ActiveRecord::Base
has_many :administrations
has_many :calendars, through: :administrations
end
class Calendar < ActiveRecord::Base
has_many :administrations
has_many :users, through: :administrations
end
class Administration < ActiveRecord::Base
belongs_to :user
belongs_to :calendar
end
连接Administration
模型具有以下属性:
id
user_id
calendar_id
role
这是我目前的路线:
devise_for :users, :path => 'account'
resources :users do
resources :calendars
end
更新
这是Calendars#create
代码:
def create
@user = current_user
@calendar = @user.calendars.create(calendar_params)
respond_to do |format|
if @calendar.save
format.html { redirect_to user_calendar_path(@user,@calendar), notice: 'Calendar was successfully created.' }
format.json { render :show, status: :created, location: @calendar }
else
format.html { render :new }
format.json { render json: @calendar.errors, status: :unprocessable_entity }
end
end
end
每当auser
创建新内容时calendar
,我都想在连接模型中为该所有者分配user
一个“所有者”。role
administration
我认为最好的方法是after_create
在calendar
模型中使用回调,如下所示:
class Calendar < ActiveRecord::Base
has_many :administrations, dependent: :destroy
has_many :users, through: :administrations
after_create :set_default_role
protected
def set_default_role
current_user.calendar.role = "Owner"
end
end
但是,当我继续尝试创建新日历时,出现以下错误:
NameError in CalendarsController#create
undefined local variable or method `current_user' for #<Calendar:0x007f88f8f26998>
Extracted source (around line #10):
def set_default_role
current_user.calendar.role = "Owner"
end
end
经过研究,我在Quora上发现了以下问题,并给出了以下答案:
该模型直接拥有当前用户的知识不是一个好习惯;这是应用程序的“状态”或与会话相关的问题。控制器应管理当前用户。
我不得不说我有些困惑:一个通用原则是通过将逻辑放置在模型中来保持控制器的皮包骨头。但是,上面的答案建议做相反的事情,因为模型不应该知道当前用户。
因此,回到我最初的问题:当用户创建新日历时,如何为用户定义默认角色?
我应该after_create
使用回调方法,还是使用其他方法而不是使用current_user
他的方法id
,或者使用完全不同的解决方案?
已更新:该模型没有current_user。从日历模型中删除set_default_role并添加到管理模型中:
class Calendar < ActiveRecord::Base
has_many :administrations, dependent: :destroy
has_many :users, through: :administrations
end
class Administration < ActiveRecord::Base
belongs_to :user
belongs_to :calendar
before_create :set_default_role
def set_default_role
self.role = "Owner"
end
end
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句