使用accepts_nested_attributes_for的嵌套表单,其中包含来自另一个表的预填充

时间:2010-04-14 14:56:03

标签: ruby-on-rails nested-forms

我正在使用Rails 2.3.5并且具有如下嵌套结构:

Lists has_many Items

Items_Features has_many Features
Items_Features has_many Items

Items_Features has a text field to hold the value of the feature

然后我有一个带有partials的嵌套表单来更新并显示它,以便它更新Lists,Items和Items_Features

我想要做的是为要素中的每一行生成输入字段,以便用户可以填写一个值,并在items_features中插入/更新。我还想在框旁边有一个标签来显示功能名称。

可能看起来像这样:

List name: Cheeses
    Item1 name: Edam
         Feature, hardness: - fill in - <= this list of features from feature table
         Feature, smell: - fill in -

如何中断好又容易的accepts_nested_attributes_for系统以显示我想要的内容?

编辑:

这是Item类的代码,现在我有一些sql:

class Item < ActiveRecord::Base
  belongs_to :list
  has_many :users
  has_many :votes
  has_many :items_features
  validates_presence_of :name, :message => "can't be blank"
  accepts_nested_attributes_for :items_features, :reject_if => lambda { |a| a.values.all?(&:blank?) }, :allow_destroy => true

  def self.get_two_random(list_id)
    Item.find_by_list_id(list_id, :limit => 2, :order => 'rand()')
  end

  def self.get_item_features(item_id)
    sql =  "select items_features.*, features.id as new_feature_id, features.name as feature_name "
    sql += "from items_features "
    sql += " right outer join features "
    sql += "  on features.id = items_features.feature_id "
    sql += " left outer join items "
    sql += "  on items.id = items_features.item_id "
    sql += "where items_features.item_id = ? or items_features.item_id is null"

    find_by_sql([sql, item_id])
  end

end

这是我的显示代码 - 我需要以某种方式将feature_id保存到新记录中:

<% form_tag item_path, :method => :put do %>
 <% for items_feature in @item_features %>
  <% fields_for "items_features[]", items_feature do |f| %>
   <%=h items_feature.feature_name %> <%= f.text_field :featurevalue %><br><Br>
  <% end %>
 <% end %>
 <p><%= submit_tag "Submit"%></p>
<% end %>

嗯,那不行 - 它打印得很好,但服务器给了我:

/!\ FAILSAFE /!\  Thu Apr 15 16:44:59 +0100 2010
Status: 500 Internal Server Error
expected Array (got Hash) for param `items_features'

当我发回信息时

1 个答案:

答案 0 :(得分:1)