我有以下型号:
class Application < ActiveRecord::Base
belongs_to :user
has_one :profile
accepts_nested_attributes_for :profile
end
class User < ActiveRecord::Base
has_one :profile
has_one :application
accepts_nested_attributes_for :profile
end
class Profile < ActiveRecord::Base
belongs_to :user
end
相应地,我的控制器中有以下代码:
class ApplicationsController < ApplicationController
...
def application_params
params.require(:application).permit(
...
profile_attributes: [:title, :name]
)
end
end
class UsersController < ApplicationController
...
def user_params
params.require(:user).permit(
...
profile_attributes: [:title, :name]
)
end
end
class ProfilesController < ApplicationController
...
def profile_params
params.require(:profile).permit(:title, :name)
end
end
正如您所看到的,在三个地方定义了相同的允许属性(:title,:name)。
有什么方法可以避免这种情况吗?例如,是否可以在变量中定义配置文件参数并使用它?
示例(不起作用):
class ApplicationController < ActionController::Base
permitted_profile_attributes = [:title, :name]
...
end
class UsersController < ApplicationController
...
def user_params
params.require(:user).permit(
...
profile_attributes: permitted_profile_attributes
)
end
end
或者我是否必须在每个控制器中单独定义允许的属性并与重复一起使用?
答案 0 :(得分:1)
这应该有效:
class ApplicationController < ActionController::Base
def permitted_profile_attributes
[:title, :name]
end
end
class UsersController < ApplicationController
...
def user_params
params.require(:user).permit(
...
profile_attributes: permitted_profile_attributes
)
end
end