Rails:虚拟属性和表单值

Cas*_*tro 5 virtual activerecord attributes ruby-on-rails

我有一个带有虚拟属性的“模型书”,可以从“书”表单中创建“编辑器”。代码如下:

class Book < ActiveRecord::Base
  has_many :book_under_tags
  has_many :tags, :through => :book_under_tags
  has_one  :editorial
  has_many :written_by
  has_many :authors, :through => :written_by

  def editorial_string
   self.editorial.name unless editorial.nil?
   ""
  end
  def editorial_string=(input)
    self.editorial = Editorial.find_or_create_by_name(input)
  end
end
Run Code Online (Sandbox Code Playgroud)

和新形式:

<% form_for(@book,
            :html => { :multipart => true }) do |f| %>
  <%= f.error_messages %>

...
  <p>
    <%= f.label :editorial_string , "Editorial: " %><br />
    <%= f.text_field :editorial_string, :size => 30  %> <span class="eg">Ej. Sudamericana</span>
  </p>
 ...
Run Code Online (Sandbox Code Playgroud)

这样,当表单数据没有通过验证时,当重新显示表单时,我丢失了在编辑字段中提交的数据,并且还创建了一个新的编辑器。我该如何解决这两个问题?我对红宝石很陌生,找不到解决方案。

更新我的控制器:

  def create
    @book = Book.new(params[:book])
    respond_to do |format|
      if @book.save
        flash[:notice] = 'Book was successfully created.'
        format.html { redirect_to(@book) }
        format.xml  { render :xml => @book, :status => :created, :location => @book }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @book.errors, :status => :unprocessable_entity }
      end
    end
  end
Run Code Online (Sandbox Code Playgroud)

rni*_*son 4

我相信它的原因是你的 Book#editorial_string 方法将始终返回“”。可以简化为以下内容:

  def editorial_string
   editorial ? editorial.name : ""
  end
Run Code Online (Sandbox Code Playgroud)

根据评论更新:

听起来你想要做嵌套表单。(请参阅api 文档中的 Accepts_nested_attributes_for)请注意,这是 Rails 2.3 中的新增功能。

所以如果你更新你的 Book 类

class Book < ActiveRecord::Base
  accepts_nested_attributes_for  :editorial
  ...
end
Run Code Online (Sandbox Code Playgroud)

(您现在也可以删除 editorial_string=, editorial_string 方法)

并将您的表单更新为如下所示

...
<% f.fields_for :editorial do |editorial_form| %>
  <%= editorial_form.label :name, 'Editorial:' %>
  <%= editorial_form.text_field :name %>
<% end %>
...
Run Code Online (Sandbox Code Playgroud)