2012-01-31 226 views
1

我有嵌套模型如下嵌套屬性在Rails的節省3.1

Project模型has_many關鍵字和關鍵字belongs_to項目

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 

查看:

<%=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%> 

我不能救keywords雖然這是節省project我可能會出錯?

關鍵字圖

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

    t.timestamps 
    end 
    end 
    end 

回答

2

試試這個在您的項目模型:

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

關鍵字 - 因爲你有的has_many關聯。

如果它不工作,檢查日誌/ development.log您的PARAMS - 你應該有這樣的事情: 「keywords_attributes」=> { 「標題」=>」 「...」}

看看這個網頁:http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

+0

欣賞你的迴應,幫助! – 2012-01-31 14:58:29