Link_to 中的 Rails 传递参数

我的帐户索引页面列出了所有帐户,每个帐户都有一个到“ + Service”的链接; 这应该将用户引导到/My _ services/new 页面,并且已经预填充了具有适当 ID 的 account _ ID 字段,这取决于在帐户索引页面上单击了哪个链接。

我在每个页面的底部都安装了 debug (params) ,在我尝试的过程中,除了/my _ services/new 页面的参数中显示的: controller 和: action 之外,我没有得到其他任何东西。

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

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

有没有人能帮我找到合适的方法?我还没有能够得到它与一些讨厌的小粗糙的东西,我尝试了。

剪辑

事实证明,如果将来有人在寻找这个答案,那么嵌套资源(可能使用 routes.rb 中的 shallow: true选项)似乎是最好的选择。我的路线 rb 现在看起来是这样的:

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

我的链接现在是这样的:

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

试试这个

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

它将根据您的需要传递 account _ id。

有关 link _ to use this http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to的详细信息,请参阅

首先,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 _ access 中的角色创建任何人的服务,那么肯定可以将两者结合起来。

希望这能帮上忙

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

如果它仍然不工作,请检查路径:

$ rake routes