在Rails 4应用程序中,我希望有一个按钮来为用户添加新的默认记录。
按钮在优先级/index.html.erb中:
<%= button_to "Add Default Values", :helper => "default_priorities" %>
助手/优先级_helper.rb中的代码
module PrioritiesHelper
def default_priorities
Priority.create("prioritycode"=>"3 Low")
Priority.create("prioritycode"=>"2 Medium")
Priority.create("prioritycode"=>"1 High")
end
end
我所犯的错误:
param is missing or the value is empty: priority
获得错误的控制器线:
params.require(:priority).permit(:user_id, :prioritycode, :description, :prioritynumber)
发布于 2015-11-12 18:01:36
很难推荐最好的解决方案,而不知道你到底想达到什么目的。当然,您应该避免在帮助器中创建记录(这不是MVC)。
我可能会在您的PrioritiesController上创建如下操作:
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的路由:
resources :priorities do
collection do
post :create_default
end
end
然后在priorities/index.html.erb中您可以这样做:
<%= button_to "Add Default Values", create_default_priorities_path(user_id: params[:user_id]) %>
根据获取用户记录的方式,上述情况可能会发生变化。例如,如果您正在使用Devise,您可能正在使用current_user,并且您不需要通过params等来传递user_id。
您还可以考虑将这些记录的创建从控制器移到优先级模型中:考虑瘦控制器、fat模型。这看起来可能是:
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
然后,您的控制器方法看起来如下:
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
https://stackoverflow.com/questions/33676758
复制相似问题