Bhushan Lodha
Bhushan Lodha

Reputation: 6862

Nested Attributes not saving in Rails 3.1

I have nested model as following

Project model has_many keywords and keyword belongs_to project

  class Project < ActiveRecord::Base

   has_many :url_list
   has_many :keyword
   accepts_nested_attributes_for :keyword, :allow_destroy => true
  end

  class Keyword < ActiveRecord::Base
   belongs_to :project
   attr_accessible :kw, :project_id 
  end

View:

  <%=form_for @project, :multipart => true do |f|%>
        <ul><li style = "width:85px; text-align: right; margin-right:5px; margin-top:5px"><%= f.label :name%></li>
        <li><%= f.text_field :name, :class => "txt_box1"%></li></ul>
        <ul><li style = "width:85px; text-align: right; margin-right:5px; margin-top:5px"><%= f.label :request_id %></li> 
        <li><%= f.text_field :request_id, :class => "txt_box1" %></li></ul>
        <ul><li style = "width:85px; text-align: right; margin-right:5px; margin-top:5px"><%= f.label :file%></li>
        <li><%= f.file_field :uploaded_file%></li></ul>

        <%= f.fields_for :keywords do |k|%> 
        <ul><li style = "width:85px; text-align: right; margin-right:5px; margin-top:5px"><%= k.label "keyword1" %></li>

        <li><%= k.text_field :kw, :class => "txt_box1" %></li></ul>


        <%end%>
        <ul><li style="width:85px; text-align: right; margin-right:5px; margin-top:5px">&nbsp;</li>
        <li style="opacity: 0.8;"><div class="space"><%= f.submit "Submit", :class=> "button"%></div></li></ul>
        <%end%>

I am not able to save keywords though it is saving project where I might have went wrong?

Keyword Schema

   class CreateKeywords < ActiveRecord::Migration
   def change
   create_table :keywords do |t|
    t.string :kw
    t.integer :project_id

  t.timestamps
  end
  end
  end

Upvotes: 1

Views: 990

Answers (1)

Nikolai Volochaev
Nikolai Volochaev

Reputation: 131

Try this in your Project model:

has_many :keywords
accepts_nested_attributes_for :keywords, :allow_destroy => true

keywords - because you have has_many association.

If it didn't work, check your params in log/development.log - you should have something like this: "keywords_attributes"=>{"title"=>" "..."}

check out this page: http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

Upvotes: 2

Related Questions