0

如何在哈希中显式设置键和值,然后在选择中使用它们?我有一个可以保存外部链接的链接模型。链接有标题和网址。我想使用标题作为键和 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
4

2 回答 2

0

我不确定您要做什么,但似乎您正在寻找这样的东西:

Link.where(title: url)

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

SELECT * FROM links WHERE title='yoururl'
于 2013-04-27T15:25:56.293 回答
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
于 2013-04-27T15:55:11.120 回答