2012-01-31 88 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