Nested form using accepts_nested_attributes_for with pre-population from another table
I'm using Rails 2.3.5 and have a nested structure as follows:
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
Then I have a nested form with partials to update and display this so that it updates Lists, Items and Items_Features
What I want to do is generate input fields for each of the rows in features so that the user can fill in a value and it gets inserted/updated in items_features. I also want a label next to the box to display the feature name.
It might look like this:
List name: Cheeses
Item1 name: Edam
Feature, hardness: - fill in - <= this list of features from feature table
Feature, smell: - fill in -
How can I interrupt the nice and easy accepts_nested_attributes_for system to display this as I want?
EDIT:
Here's the code for the Item class now i've got some sql in there:
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
Here's my display code - I need to save the feature_id into new records somehow:
<% 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 %>
Hmm, that isn't working - it prints out fine but then the server gives me:
/!\ FAILSAFE /!\ Thu Apr 15 16:44:59 +0100 2010
Status: 500 Internal Server Error
expected Array (got Hash) for param `items_feature开发者_如何学Gos'
When I post it back
Try the examples here
http://github.com/ryanb/complex-form-examples
精彩评论