簡體   English   中英

ActiveModel的自定義屬性的attr_accessor用法

[英]attr_accessor usage for a custom attribute of ActiveModel

我需要使用復選框(布爾字段)實現帶有自定義字段 (在db中沒有引用)的表單。

如果選中了該復選框,則后端必須編寫特定的多對多行並將其指向更新的對象。

問題是我的article.rb中的 setter方法沒有在表單發布中訪問。

article.rb

class Article < ActiveRecord::Base
  attr_accessor :highlight

  def highlight
  end

  def highlight=(arg)
    puts "NO ACCESS"
  end
end

_form.html.erb

<%= semantic_form_for [:admin, @article] do |f| %>
  <%= f.input :title, :label => "Title" %>
  <%= f.input :text, :as => :ckeditor %>
  <%= f.input :highlight, :as => :boolean, :label => "Highlight" %>

article.rb(active_admin)

ActiveAdmin.register Article do
  form partial: 'form'
  permit_params do
    permitted = [:title, :text, :highlight]
    permitted
  end
end

Javkhlan, attr_accessor :highlight是以下格式的縮寫

def highlight
  @hightlight
end

def highlight=(highlight)
  @highlight = highlight
end

所以,你的代碼

def highlight
end

def highlight=(arg)
  puts "NO ACCESS"
end

只需重寫attr_accessor生成的方法。 嘗試刪除這兩種方法,您會很高興的

去掉

attr_accessor:突出顯示

並檢查

暫無
暫無

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

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