2014-03-05 90 views
0

我有兩個模型一個Topic和Topic_Content。嵌套屬性不會保存在數據庫中

用下面的代碼

路線

resources :topics do 
    resources :topic_contents 
    end 

主題

class Topic < ActiveRecord::Base 
has_one :topic_content 
accepts_nested_attributes_for :topic_content 
end 

TopicContent

class TopicContent < ActiveRecord::Base 
belongs_to :topics 
end 

控制器

class TopicsController < ApplicationController 

def new 
    @topic = Topic.new 
end 

def create 
    # render text: params[:topic].inspect 
    @topic = Topic.new(topic_params) 
    @topic.save 
end 

private 

def topic_params 
    params.require(:topic).permit(:title, topic_content_attributes: [:text]) 
end 

end 

查看

<%= form_for @topic do |f| %> 
<%= f.label 'Topic:' %> 
<%= f.text_field :title %> 
<%= f.fields_for :topic_contents do |tf| %> 
<%= tf.label :text %> 
<%= tf.text_area :text %>  
<% end %>   
<%= f.submit %> 
<% end %> 

冠軍將在主題表保存正確的,但topic_content(文本)將不會保存在數據庫,我找不到問題。

回答

1

我不是一個Rails的專家,但我敢肯定,你需要建立在你的控制器的關聯。

在新的和編輯的操作,你需要有:

def new 
    @topic = Topic.new 
    @topic_content = @topic.build_topic_content 
end 

因爲這是一個HAS_ONE/belongs_to的你需要把它看上去那樣。如果它是一個很多的關聯,你會用@topic_content = @ topic.topic_contents.build來構建它。

我非常確定這只是在正確的控制器中建立關聯的問題,我相信對您而言,它是主題控制器。

+0

Thx,快速的回答它幫助我很多!一個問題留給我。它設置外鍵正確,但**:文本**不是。 – dot

+0

問題已解決 – dot

1

你的觀點應該是如下:

f.fields_for :topic_content do |content_fields| 
         ^