【问题标题】:Rails, get object association when using build (object still not in database), the DRYRails,使用构建时获取对象关联(对象仍然不在数据库中),DRY
【发布时间】:2012-11-16 21:14:32
【问题描述】:

我正在构建一个使用一种元问题模型的报告系统。问题预先保存在数据库中,然后根据报告的类型从数据库中提取一些问题。

想要保持干燥,我正在想办法将Variable 模型的信息传递给我的report_header,但无济于事。

new 操作中我有:

  reportBody = @report_head.report_bodies.build(:variable_id => a.id)
  @report_head.variables #modified, thx.

我只需要以DRY 的方式将属性从Variable 传递给report_head。

如果您需要了解我的模型:

class Variable < ActiveRecord::Base
  attr_accessible :id,:break_point, :description, :name, :time_frequency, :v_type
  has_many :report_bodies
  has_many :report_heads, :through => :report_bodies   
end

class ReportHead < ActiveRecord::Base
  attr_accessible :email, :name , :report_bodies_attributes, :report_bodies, :variables_attributes
  has_many :report_bodies
  has_many :variables, :through => :report_bodies   
  accepts_nested_attributes_for :report_bodies
end

class ReportBody < ActiveRecord::Base
  attr_accessible :report_head_id, :variable_value, :variable_id, :variables_attributes, :report_heads
  belongs_to :report_head
  belongs_to :variable
end

更新

我按照建议更新了模型,并修改了调用变量的方式。但是,如果我执行以下操作,我仍然对如何在视图中使用它感到困惑:

   <%= f.fields_for :variables do |variable| %>
       <%= variable.text_field :name, :value => :name, :class => 'text_field' %>  
   <% end %>

它打印一个字符串而不是实际名称。

【问题讨论】:

    标签: ruby-on-rails-3 dry


    【解决方案1】:

    您定义了错误的名称关联,您的 ReportBody 关联应该是:

    belongs_to :report_head 
    belongs_to :variable 
    

    这是不正确的:

    @report_head.report_bodies.build(:variable_id => a.id,:report_head_id =>@report_head.id) 
    

    改成:

    @report_head.variables.build(:variable_id => a.id)
    

    这样更好,你不必设置report_head_id。这是错误的:

    @report_head.report_bodies.variables
    

    如果你想得到所有变量属于@report_head,你只需要使用:

    @report_head.variables
    

    【讨论】:

    • 别担心,我会的,你认为你可以在最后一部分帮助我吗?
    • 你的表单是用来创建新对象的吗? fields_for 只用于表单创建新对象,你只需要&lt;%= variable.text_field :name %&gt;
    • 是的,我的表单用于创建报告,但是我的变量已经存在。这样做会给我错误undefined local variable or method 'variable' for #&lt;#&lt;Class:0xaea4fd4&gt;:0xb4b21d8&gt;
    • 顺便说一句,我在执行@report_head.report_bodies.build(:variable_id => 1) 之后使用控制台测试了@report_head.variables 的输出,但是它返回了一个空对象
    • 不,我的回答是,您不能使用@report_head.report_bodies.build(:variable_id =&gt; 1),只能使用@report_head.variables.build(name: 'something') 创建新变量并插入到ReportBody。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多