首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >rails 4在助手中创建记录

rails 4在助手中创建记录
EN

Stack Overflow用户
提问于 2015-11-12 16:44:30
回答 1查看 82关注 0票数 0

在Rails 4应用程序中,我希望有一个按钮来为用户添加新的默认记录。

按钮在优先级/index.html.erb中:

代码语言:javascript
运行
复制
<%= button_to "Add Default Values", :helper => "default_priorities" %>

助手/优先级_helper.rb中的代码

代码语言:javascript
运行
复制
module PrioritiesHelper
  def default_priorities
    Priority.create("prioritycode"=>"3 Low")
    Priority.create("prioritycode"=>"2 Medium")
    Priority.create("prioritycode"=>"1 High")
  end
end

我所犯的错误:

代码语言:javascript
运行
复制
param is missing or the value is empty: priority

获得错误的控制器线:

代码语言:javascript
运行
复制
  params.require(:priority).permit(:user_id, :prioritycode, :description, :prioritynumber)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-11-12 18:01:36

很难推荐最好的解决方案,而不知道你到底想达到什么目的。当然,您应该避免在帮助器中创建记录(这不是MVC)。

我可能会在您的PrioritiesController上创建如下操作:

代码语言:javascript
运行
复制
def create_default

  # Grab the user you want
  @user = User.find(params[:user_id])

  # Create the priories through the association
  @user.priorities.create(prioritycode: "3 Low")
  @user.priorities.create(prioritycode: "2 Medium")
  @user.priorities.create(prioritycode: "1 High")

  redirect_to priorities_path, notice: "Defaults created!"
end

定义一个类似于routes.rb的路由:

代码语言:javascript
运行
复制
resources :priorities do
  collection do
    post :create_default
  end
end

然后在priorities/index.html.erb中您可以这样做:

代码语言:javascript
运行
复制
<%= button_to "Add Default Values", create_default_priorities_path(user_id: params[:user_id]) %>

根据获取用户记录的方式,上述情况可能会发生变化。例如,如果您正在使用Devise,您可能正在使用current_user,并且您不需要通过params等来传递user_id。

您还可以考虑将这些记录的创建从控制器移到优先级模型中:考虑瘦控制器、fat模型。这看起来可能是:

代码语言:javascript
运行
复制
def self.create_defaults_for(user)
  create(prioritycode: "3 Low", user: user)
  create(prioritycode: "2 Medium", user: user)
  create(prioritycode: "1 High", user: user)
end

然后,您的控制器方法看起来如下:

代码语言:javascript
运行
复制
def create_default

  # Grab the user you want
  @user = User.find(params[:user_id])

  # Create the priories through the association
  Priority.create_defaults_for(@user)

  redirect_to priorities_path, notice: "Defaults created!"
end
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33676758

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档