Rails-在link_to中传递参数


73

我的帐户索引页面列出了所有帐户,每个帐户都有指向“ +服务”的链接;这应将用户定向到/ my_services / new页面,并根据在Accounts索引页面上单击的链接,用适当的ID预先填充account_id字段。

我在每个页面的底部都有debug(params),根据我的尝试,除了/ controller和:action外,/ my_services / new页面的参数中没有显示其他内容。

我一直在尝试的链接是这样的:

link_to "+ Service", "my_services/new", :account_id => acct.id

然后,我在服务控制器中也有逻辑:

def new
  @my_service = MyService.new
  if params[:account_id]
    @my_service.account_id = params[:account_id]
  end
end

有人可以帮助您采取适当的方法吗?我还无法通过我尝试过的一些讨厌的小技巧来解决这个问题。

编辑

事实证明,如果将来有人在看这个答案,嵌套资源(可能带有shallow: trueroutes.rb中的选项)似乎是解决之道。我这部分的routes.rb现在看起来像这样:

resources :accounts, shallow: true do
  resources :services
end

我的链接现在看起来像这样:

<%= link_to "+ Service", new_service_path(:service => { :account_id => @account.id } ) %>

Answers:


109

首先,link_to是html标签帮助器,其第二个参数是url,后跟html_options。您想要将account_id作为URL参数传递到路径。如果您在routes.rb中正确设置了命名路由,则可以使用路径助手。

link_to "+ Service", new_my_service_path(:account_id => acct.id)

我认为最佳实践是将模型值作为嵌套在其中的参数传递:

link_to "+ Service", new_my_service_path(:my_service => { :account_id => acct.id })

# my_services_controller.rb
def new
  @my_service = MyService.new(params[:my_service])
end

并且您需要控制允许account_id用于“质量分配”。在rails 3中,您可以使用功能强大的控件来过滤控制器所属的控制器中的有效参数。我强烈推荐。

http://apidock.com/rails/ActiveModel/MassAssignmentSecurity/ClassMethods

另请注意,如果用户未随意设置account_id(例如,用户只能为自己的单个account_id提交服务,则更好的做法是不通过请求发送该服务,而是通过添加一些内容在控制器内进行设置喜欢:

@my_service.account_id = current_user.account_id 

如果只允许用户使用自己的帐户创建服务,但允许管理员使用attr_accessible中的角色来创建任何人,则可以肯定地将两者结合起来。

希望这可以帮助


我想知道这是否行得通link_to“ Service”,“ my_services / new?account_id =” + acct.id
Zia Ul Rehman Mughal


2
link_to "+ Service", controller_action_path(:account_id => acct.id)

如果仍然无法正常工作,请检查路径:

$ rake routes
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.