简体   繁体   English

Ruby on Rails覆盖默认访问器

[英]Ruby on Rails Overwriting default accessors

In my model i say: 在我的模型中,我说:

def dag
  'test'
end

But when I loop all the records and uses 但是当我循环所有记录和使用时

f.text_field :dag

I still do not get the value of "test" ... I get the value from the database. 我仍然没有获得"test"的价值……我从数据库中获得了价值。 How can I overwrite the default getter for forms? 如何覆盖表单的默认getter? I works when I say 我说的时候工作

Model.dag # returns 'test'

Although your example doesn't indicate this, have you defined dag as a class method instead of an instance method? 尽管您的示例并未说明这一点,但您是否已将dag定义为类方法而不是实例方法? Model.dag implies that it's a class method which is not what you want. Model.dag暗示它不是您想要的类方法。

If you could give us a little more code, it will be more useful to find the correct answer for you. 如果您可以给我们更多的代码,那么为您找到正确的答案将更加有用。

Said so, I suspect you have declared your dag method as protected or private method. 这么说,我怀疑您已将dag方法声明为保护方法或私有方法。 Have a look if there is a private (or protected ) keywork above the dag method declaration on model's code: if so, the method is private (or protected), thus it cannot be accessed by your template... 看一下模型代码的dag方法声明上方是否有private (或protected )键:如果是,则该方法是私有(或受保护),因此模板无法访问该方法...

The class: 班级:

class DenLangeKamp < ActiveRecord::Base
  belongs_to :liga, :class_name => "DenLangeLiga"

  DAYS = { "Man" => 1, "Tir" => 2, "Ons" => 3, "Tor" => 4, "Fre" => 5, "Lør" => 6, "Søn" => 7 }

  def dag
    DAYS.invert[reader_attribute(:dag)]
  end

  def dag=(dag)
    write_attribute(:dag, DAYS[dag])
  end
end

and then the form looks like this: 然后表单如下所示:

.........
<% liga_form.fields_for :kampe do |kamp_form| %>
  <tr>
    <td><%= kamp_form.text_field :dag %></td>
.........

I am saving the day as a number in the DB, so I can sort by the day. 我将日期保存为数据库中的数字,因此可以按日期进行排序。 "dag" is "day" in English. “ dag”在英语中是“ day”。

When I say like "DenLangeKamp.first.dag" I get the right return (like "Man", "Tir", etc) But in the form, I am getting the number instead! 当我说“ DenLangeKamp.first.dag”时,我得到正确的回报(例如“ Man”,“ Tir”等),但是在表格中,我得到的是数字! So it does not seem like it actually "overwrites" the getter method correctly. 因此,看起来它实际上并没有正确地“覆盖” getter方法。

I have the same problem. 我也有同样的问题。 The overridden functions seem to work on the index and show but in the edit the form isn't using the overridden function. 被覆盖的函数似乎可以在索引上显示,但是在编辑中,表单没有使用被覆盖的函数。 It seems to be getting a different way bypassing the overridden functions. 绕过重写的功能似乎有另一种方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM