Do I treat this as an array or a hash?

时间:2015-05-12 22:18:43

标签: arrays ruby ruby-on-rails-3 hash model

I have two models: 22 55 and class User < ActiveRecord::Base. If I write:

class Tips < ActiveRecord::Base

or

user.each do |...|

Should I treat either as an array or a hash? How will I know?

I would post the model for user and tips, but they are very long. Any help is appreciated! Thanks in advance!!!

4 个答案:

答案 0 :(得分:1)

Objects inheriting from update tracks set album_id = a.id from albums a where tracks.album_name = a.name are ActiveRecord Objects and should be treated as such. A comprehensive list of methods can be found here. You can optionally convert AR objects to arrays (using the ActiveRecord::Base built-in) or hashes (by using your own hash implementation depending on how you want the keys and values)

答案 1 :(得分:1)

我认为你的问题可以通过多种方式得到改善。如果我理解正确:

你有一个班级

class User < ActiveRecord::Base
  has_many :tips
  ...
end

class Tip < ActiveRecord::Base
  belongs_to :user
  ...
end

所以如果你有一个Tip类的实例(该类应该是单数,除非这个类的每个实例代表许多提示) - 让我们调用这个实例@tip - 它只属于一个用户。所以@tick.user将真的是这个用户 - 没有什么可以迭代(没有像哈希或数组)。但用户本身有很多提示。所以@ user.tips就像一个数组。虽然@ user.tips不是一个数组(只需在rails控制台中尝试类似:

@user = User.first
@user.tips.class

),它在大多数情况下表现得像一个数组。如果你需要一个真正的数组,你可以使用

@user.tips.to_a

但在大多数情况下,你应该坚持协会本身。

答案 2 :(得分:0)

For what it seems you're trying to do, treat it as an array. In fact, you can do LayoutInflator's inflate(), and it'll be an array.

答案 3 :(得分:0)

Programming languages vary as to their exact meaning of "array" vs. "hash," but Ruby (unlike PHP, say ...) follows Perl:

  • A "hash" is a collection of things, indexed by an arbitrary "key."
  • An "array" is an ordered collection of things, indexed by an integer.

Therefore, "what makes the most sense, for you, in this case?" If "this collection-of-things is naturally 'ordered,' such that the "most comfy" way to think of it is "#1, #2, #3 ...," then a Ruby <table id="users-table" class="table table-hover table-striped"> <thead> <tr> <th>#</th> <th>First Name</th> <th>Last Name</th> </tr> </thead> </table> $(function() { $('#users-table').dataTable({ ajax: '@Url.Action("ListUsers", "Businesses",null,Request.Url.Scheme)' }); }); would be called for. Whereas, if one would (instead) ordinarily think of, "the entry for 'Tom,' 'Dick,' or 'Harry,'" the best representation would be a array.

Superficially, since I see no obvious "key," the best answer is probably: an hash.