2013-04-27 31 views
0

如何显式设置密钥和哈希值,然后使用select?我有一个链接模型,可以保存外部链接。一个链接有一个标题和一个网址。我想使用标题作为键和url作为值。显式设置键和值的选择

--------------------- UPDATE ------------------------ -

这项工作..

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

这就是我想要的。也许有更好的方法。

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 
0

我不完全相信你会的东西,但好像你正在寻找的东西是这样的:

Link.where(title: url) 

...其中URL是一些局部变量。这将生成类似于以下的SQL语句:

SELECT * FROM links WHERE title='yoururl'