如何在散列中显式设置键和值,然后在选择中使用它们?我有一个链接模型,可以保存外部链接。链接有标题和网址。我想使用标题作为键,将url作为值。
这项工作..
links = Link.all
link_array = []
links.each do |link|
link_array << [link.title,link.url]
end
但是,现在这就是问题。我想将此数组连接到另一个数组,以便可以从单个表单选择中选择两个模型。像这样......
a = PagesController.action_methods
# this grabs each action from the pages controller that will later be used as a route
b = a.select {|s| s.include? "callback"}
c = a - b
# b and c removes any position in the array that includes the word 'callback' so that only actions defined in the controller are returned
links = Link.all
link_array = []
links.each do |link|
link_array << [link.title,link.url]
end
@all_links = c + link_array
# desired result is an array used in a single form select containing both external links and internal links
答案 0 :(得分:0)
我不确定你的目的是什么,但看起来你正在寻找这样的东西:
Link.where(title: url)
...其中url是一些局部变量。这将生成类似于以下内容的SQL语句:
SELECT * FROM links WHERE title='yoururl'
答案 1 :(得分:0)
这就是我想要的。也许有更好的方法。
a = PagesController.action_methods
b = a.select {|s| s.include? "callback"}
c = a - b
@c_array = []
c.each do |p|
@c_array << [p, "#{p}_path"]
end
links = Link.all
@link_array = []
links.each do |link|
@link_array << [link.title, link.url]
end
@all_links = @c_array + @link_array
包含内部路由(到页面操作)和指向URL的外部链接的单个数组。现在,在第三个模型中,我可以有一个标题为“pathto”的字符串列,并存储路径(作为字符串)或url。然后,在帮助器中执行此操作:
def send_route(pathto)
if pathto.include? "http"
pathto # just go to the url
else
self.send( pathto ) # create a route from the string stored in the db .. i.e. "home_path"
end
end