簡體   English   中英

Rails 3.2,虛擬訪問器和棄用警告

[英]Rails 3.2, virtual accessor and deprecation warning

我真的對Rails 3.2中的虛擬屬性感到困惑,我的所有研究都沒有使事情變得更清楚。

# input model
class Input < ActiveRecord::Base

  # Attributes --------------------
  attr_accessible :title, :parent
  attr_accessor :parent

  def parent=(id)
    wrtite_attribute(:parent, id.to_i)
    self.parent = id.to_i
    self[:parent] = id.to_i
    @parent = id.to_i # seems to be the only one working. Why?
  end

end

# inputs controller
class InputsController < ApplicationController

  def new
    @input = Input.new({
      start_date: @current_scope_company.creation_date,
      parent: 'bla'
    })

    @input.parent = 'bla'
    @input[;parent] = 'bla'

  end
end

# inputs table
create_table "inputs", :force => true do |t|
  t.string   "title"
  t.datetime "created_at",                        :null => false
  t.datetime "updated_at",                        :null => false
end

上面,我已經整理了幾乎所有在互聯網上找到的替代方法。 這不是我運行的代碼,只是同一件事的幾個版本。 雖然,無論我如何嘗試,我都會收到以下警告:

DEPRECATION WARNING: You're trying to create an attribute 'parent'. Writing arbitrary attributes on a model is deprecated. Please just use 'attr_writer' etc.

有時,我什至無法獲得足夠的stack level too deep 我很想了解屬性是如何工作的。

1 / attr_accessorattr_writerattr_reader對嗎? 為什么要求我在警告中使用attr_writer

2 /我應該如何從模型中寫入屬性(以及原因)

3 /我應該如何從控制器寫入屬性(以及為什么)

非常感謝!

更新

經過進一步測試后,看起來正確的方法是@parent = id.to_i 我仍然很想得到為什么的解釋。 我真的很困惑為什么要self. 不會工作。

Atttr_accessor應該沒問題。 因此,在您的模型中,看起來您正在嘗試以四種不同的方式來做同樣的事情:

def parent=(id)
  write_attribute(:parent, id.to_i)
  self.parent = id.to_i
  self[:parent] = id.to_i
  @parent = id.to_i            # <- all these are redundant and scary
end

(此外,在您的控制器中,您看起來好像也在嘗試以不必要的方式來做相同的事情。)此外,我非常確定語法'def parent =(id)'僅適用於真實屬性。 從我的經驗來看 ,您只是對虛擬屬性執行以下操作:

def parent
  @id.to_i
end

來自“ id”的地方應該進入“ parent”(父母)? 虛擬屬性必須通過真實屬性或關聯的真實屬性以某種方式與實際存儲在數據庫中的內容相關。 如果您多解釋一些實際應該從中計算出的父對象,那么幫助會更容易。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM