在模型中定义方法的目的是什么?

时间:2014-08-13 21:25:49

标签: ruby-on-rails

在模型中定义方法的目的是什么,例如这里的示例?这对我有什么影响?我的印象是模型中只定义了模型的字段。

class Bean
  include Mongoid::Document
  field :name, type: String
  field :roast, type: String
  field :origin, type: String
  field :quantity, type: Float

  has_many :pairings
  #  has_many :pastries

  def pastries
    Pastry.find pastry_ids
  end
  #accepts_nested_attributes_for :pastries

  def pastry_ids
    pastry_ids_array = []
    self.pairings.each do |one_pairing|
      if one_pairing.pastry_id
        pastry_ids_array.push one_pairing.pastry_id
      end 
    end
    pastry_ids_array 
  end

  def pastry_ids=(list)
    self.pairings.destroy
    list.each do |pastry_id|
      self.pairings.create(pastry_id: pastry_id)
    end
  end

  # some way of showing a list
  def pastry_list
    pastries_string = ""
    pastries.each do |one_pastry|
      pastries_string += ", " + one_pastry.name
    end
    pastries_string.slice(2,pastries_string.length - 1)
    pastries_string
  end

end

1 个答案:

答案 0 :(得分:3)

我不知道你是否知道足够的红宝石,但让我们说你不知道。这是一个基本的课堂问题?在模型上定义方法就像拥有帮助器一样。让我们说你有

class CanadianPopulation 

  attr_accessor :population, :number_of_french_speaker, :number_of_english_speaker

  def initialize(a,b,c)
    @population = a
    @number_of_french_speaker = b
    @number_of_english_speaker = c
  end

  def total_people_that_have_a_different_mother_tongue
    #Canadian who speak english or french but have a different mother tongue
    self.population - (self.number_of_french_speaker + self.number_of_english_speaker)
  end
end

census_2014 = CanadianPopulation.new(34_000_000, 4_000_000, 12_000_000)

让我们说你没有方法total_people_that_have_a_different_mother_tongue你将如何找回拥有不同母语的加拿大人总数?你会自己做一个计划

<p>Canadian who speak english or french but have a different mother tongue
<br>
<%= @census = @census.population - (@census.number_of_english_speaker + @census.number_of_french_speaker) %>
</p>

你的视图或你的控制器不应该做很多逻辑(计算),这就是为什么你在模型(或类)中有一个方法的原因之一应该是这样的

<p>Canadian who speak english or french but have a different mother tongue
<br>
<%= @census.total_people_that_have_a_different_mother_tongue %>
</p>

对于问题的第二部分,这些方法的作用是什么。终端上的rails c -s比调用或创建新的实例模型Bean并检查它的作用(输出/结果)

Bean.first
b = _
b.pastries
b.pastry_ids
b.pastry_list

编辑:@ paul-richher建议维护瘦控制器