繁体   English   中英

视图中无法访问模型中的Rails方法

[英]Rails methods in model not accessible in view

我整天都在打闹。

我有一个模型类,它通过has_many连接连接到另一个。 它可以正常工作,但是当我尝试从类中访问非db方法时,出现一个错误,该模型不包含该方法。 我将方法放入attr_accessible中,因此我认为它应该是可访问的。

这是头等舱的模型:

class Recipe < ActiveRecord::Base
  validates :name,  :presence => true,
                    :length   => { :maximum => 100 }

  attr_accessible :ingredient_recipes_attributes

  has_many :ingredient_recipes, :foreign_key => "recipe_id"
  has_many :ingredients, :through => :ingredient_recipes

  accepts_nested_attributes_for :ingredient_recipes, :allow_destroy => true
end

第二种模式:

class IngredientRecipe < ActiveRecord::Base
  attr_accessor :ingrNameFromUser

  set_primary_key :ingredient_id, :recipe_id

  attr_accessible :ingrNameFromUser, :readable_qty, :ingredient_description

  belongs_to :recipe, :foreign_key => "recipe_id"
  belongs_to :ingredient, :foreign_key => "ingredient_id"
  # belongs_to :ndbfoodde, :foreign_key => "ingredient_id"kki"

  delegate :description, :to => :ingredient, :prefix => "ingredient", :allow_nil => true

  def readable_qty
    qty.to_s + " gr."
  end

  def readable_qty=(qty)
    self.qty = qty.to_f + 2
  end
end

当我尝试通过这样的视图访问visible_qty时:

 <% f.fields_for :ingredient_recipes do |rif| %>        
          <td>            

              <%= rif.autocomplete_field :ingrNameFromUser, recipes_autocomplete_ingredient_description_path, :value => @recipe.ingredient_recipes[i].ingrNameFromUser, :width=>1000, :size=>60 %>
          </td>  

          <td>         
          <%= rif.text_field :readable_qty %>
        </td>

我收到一个错误:

undefined method `readable_qty' for #<IngredientRecipe:0x00000103322068>

Extracted source (around line #59):

56:           </td>  
57:           
58:           <td>         
59:           <%= rif.text_field :readable_qty %>
60:         </td>
61:         
62:         <td>

有人可以看到我在做什么吗?

乍一看,我想说的是,给定的readable_qty是一个虚拟属性(即它不在数据库中,并且具有作为setter和getter的实例方法,您应该将其从attr_accessible列表中删除。此列表定义了哪些属性存储在可以通过批量分配来更新数据库。

但是readable_qty不是数据库字段,因此它不属于列表。

尝试添加

attr_accessor :readable_qty

到IngredientRecipe。

如果您在生产模式下运行服务器,并且已对模型进行了更改,则该模型将不会自动重新加载,并且新方法将不可用。 您必须重新启动服务器才能使其生效。

暂无
暂无

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

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