【问题标题】:Expose a has_many relationship through a single text field通过单个文本字段公开 has_many 关系
【发布时间】:2013-10-05 14:07:07
【问题描述】:

我有一个“有很多”B 的模型 A。

class A < ActiveRecord::Base
  has_many :B
  attr_accessible :title
end
class B < ActiveRecord::Base
  belongs_to :A
  attr_accessible :name
end

我想在我的“编辑 A”表单中添加一个字段:一个文本区域,我将在其中为每一行输入我 B 的 :name,然后在提交时解析该字段并处理每一行。

问题是,我该怎么做?

编辑

关注Rails - Add attributes not in model and update model attribute我来到了这里:

class A < ActiveRecord::Base
  has_many :B
  attr_accessible :title

  def my_b
    list = ""
    self.B.each do |b|
      list += "#{b.name}\n"
    end
    logger.debug("Displayed Bs : " + list)
    list
  end

  def my_b=(value)
    logger.debug("Saved Bs : " + value)
    # do my things with the value
  end

end

def bees=(value) 似乎从未被解雇。

我做错了什么?

编辑 2

我的实际代码在这里可见:https://github.com/cosmo0/TeachMTG/blob/edit-deck/app/models/deck.rb

【问题讨论】:

    标签: ruby-on-rails ruby accessor


    【解决方案1】:

    你可以放一个:attr_accessor,比如:

    class A < ActiveRecord::Base
      has_many :B
      attr_accessible :title
      attr_accessor :field_of_happiness
    
      def field_of_happiness=(value)
        # override the setter method if you want 
      end
    
      def field_of_happiness(value)
        # override the getter method if you want 
      end
    end
    

    Reference: attr_accessor api doc

    它在某种程度上对你有帮助?

    【讨论】:

    • 我实际上是在测试它。正如我在问题中编辑的那样,setter 似乎从未被解雇。
    【解决方案2】:

    哦,天哪。原来问题不在于模型,而在于控制器……我忘了在 update 方法中添加一个简单的行来将我的 POST 值分配给我的类字段……

    无论如何,最终的解决方案是这样的:

    在我的控制器中:

      def update
        @a.whatever = params[:a][:whatever]
        @a.my_b = params[:a][:my_b]
        @a.save
      end
    

    在我的模型中:

    class A < ActiveRecord::Base
      has_many :B
      attr_accessible :whatever
    
      def my_b
        list = ""
        self.B.each do |b|
          list += "#{b.name}\n"
        end
        list
      end
    
      def my_b=(value)
        # parse the value and save the elements
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-06
      相关资源
      最近更新 更多