2013-04-27 35 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'