我正在使用允许用户创建项目的 Rails 应用程序。在这些项目中,用户可以制作列表。我试图弄清楚如何让用户从项目索引页面中选择他们的“默认工作项目”。然后这将在整个应用程序中传播,仅显示与当前项目关联的列表。制作这样的东西的最佳方法是什么。
最佳答案
您可以通过将 default_working_project_id
字段添加到您的用户表中来轻松实现这一点。
然后在你的 Controller 索引集中:
@default_working_project = current_user.default_working_project
在你的用户模型中添加:
belongs_to :default_working_project, class_name: Project, foreign_key: :default_working_project_id
您可以创建自己的 Action 。在你的路线文件中:
resources :projects do
member do
get 'set_default'
end
end
在你的projects_controller
中:
def set_default
project.find params[:id]
current_user.default_working_project_id = project.id
respond_to do |format|
if current_user.save
format.html { redirect_to projects_path }
else
format.html { render 'index', notice: "your error message" }
end
end
end
在你的 View 中添加
link_to 'set default', set_default_project_path(project.id)
已更新
从用户中删除当前的默认项目 ID:
您可以通过一些方法来实现这一点,例如:
在您的项目模型中
如果您有项目属于用户的关系,请尝试此操作。
def is_a_current_project?
self.id == self.user.default_working_project_id
end
然后创建一个after_destroy :remove_current_project_relation
回调方法。
还有方法,我建议将它添加到您的私有(private)方法中:
def remove_current_project_relation
if is_a_current_project?
self.user.default_working_project = nil
end
end
关于ruby-on-rails - Rails 允许用户设置默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34274592/