Rails - 如何将值“合并"或附加到 URL 中的数组? [英] Rails - How do I 'merge' or append a value to an array within the URL?

查看:29
本文介绍了Rails - 如何将值“合并"或附加到 URL 中的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 URL 中传递一个数组,该数组工作正常,但我想知道如何插入或删除某些值?

I am trying to pass an array in the URL, which is working fine, but I'd like to know how I can then insert or remove certain values?

例如,我有一个如下所示的链接:

For example, I have a link that looks like:

http://localhost:3000/pins?genre_ids[]=1,2,3

我想构建一组可以在此 URL 数组中插入或删除数字的链接.

I would like to build a set of links that can insert or remove numbers from this URL array.

目前,我拥有的每个链接都只是完全改变了流派_ids[] 的值,我想在其中添加或根据需要删除.这是我构建链接的代码...

At the moment, each link I have simply changes the genre_ids[] value completely, where as I'd like to add to it, or take away as needed. This is my code to build the link...

<%= link_to genre[0].title, pins_path( params.merge({ :genre_ids => [genre[0].id] }) ) %>

我认为我所追求的是类似于 params.merge() 但对于 params[:genre_ids]

I think what I'm after is something like params.merge() but for the value of params[:genre_ids]

我希望你能明白我的意思?如果当前 URL 读取 /pins?genre_ids[]=1,2,3 我希望这样我构建的每个链接都包含此当前链接,并在此数组中添加另一个数字,所以它看起来像 /pins?genre_ids[]=1,2,3,4

I hope you can understand what I mean? If the current URL reads /pins?genre_ids[]=1,2,3 I'd like it so that each link I build includes this current link, with the addition of another number into this array, so that it would look like /pins?genre_ids[]=1,2,3,4

任何帮助将不胜感激.我来自 CF 背景,所以我仍在尝试了解 Ruby 和 Rails.我在 Ruby 2 中使用 Rails 4.

Any help would be greatly appreciated. I'm from a CF background, so I'm still trying to get my head around Ruby and Rails. I am using Rails 4 with Ruby 2.

谢谢,迈克尔.

推荐答案

您正在覆盖 genre_ids 数组.您需要组合两个数组,您可以使用 + 运算符:

You are overwriting your genre_ids array. You need to combine the two arrays, which you can do using the + operator:

params[:genre_ids] + [genre[0].id]

我认为这可以解决问题:

I think this will do the trick:

<%= link_to genre[0].title, pins_path( params.merge({ :genre_ids => (params[:genre_ids] + [genre[0].id]) }) ) %>

但是,应该注意的是,您最终可能会得到重复的数组对象值.您可能需要考虑使用联合"运算符 |.

However, it should be noted that you can end up with duplicate array object values. You may want to consider using the "union" operator |.

示例:

first = [1,2,3,4]
second = [3,4,5,6]
first + second #=> [1, 2, 3, 4, 3, 4, 5, 6]
first | second #=> [1, 2, 3, 4, 5, 6]

所以也许你的链接应该是:

So maybe your link should be:

<%= link_to genre[0].title, pins_path( params.merge({ :genre_ids => (params[:genre_ids] | [genre[0].id]) }) ) %>

这篇关于Rails - 如何将值“合并"或附加到 URL 中的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆