2015-07-19 98 views
2

我有一个模型Note和它的属性是subjectcontent问题是,创建一个新的笔记时,内容变得nil模型内容没有得到保存

型号/ notes.rb

belongs_to :user 

scope :english, lambda { where("note.subject = ?", "english") } 
scope :math, lambda { where("note.subject = ?", "math") } 

控制器/ notes.rb

def new 
    @note = current_user.notes.new 
    respond_with(@note) 
end 

def create 
    @note = current_user.notes.new(note_params) 
    @note.save 
    redirect_to user_note_path(current_user.id, @note) 
end 

private 
def set_note 
    @note = current_user.notes.find(params[:id]) 
end 

def note_params 
    params.permit(:content, :subject, :user_id) 
end 

参数提交后/笔记/新形式

Parameters: {.."note"=>{"content"=>"new note"}, "subject"=>"english", "commit"=>"Submit", "user_id"=>"1"} 

笔记/ _form.html。 erb

<%= form_for([current_user, @note]) do |f| %> 

    <%= f.label :content %> 
    <%= f.text_area :content %> 

    <%= f.label :subject %> 
    <%= select_tag(:subject, options_for_select(["english", "math"])) %> 

    <%= f.submit "Submit"%> 

<% end %> 
+0

当你说“的内容成为无“内容属性保存无或所有属性保存为零? – Pavan

+0

内容属性保存为零 –

+0

请张贴您的表单代码 – Pavan

回答

2

默认情况下,使用objectform_for(@object) form_builder会“命名空间”中的所有领域,这就是为什么你被建议使用params.require(:note),这样才能挑:note

换句话说命名空间的各个领域,有

之间的差异
<%= f.select(:subject, options_for_select(["english", "math"])) 
<%= select_tag(:subject, options_for_select(["english", "math"])) %> 

使用f.something:user

使用something_tag下将命名空间将不会命名空间

因此,要彻底解决与最佳实践的代码,您应该使用

<%= f.select(:subject, options_for_select(["english", "math"])) 

您表格和

params.require(:note).permit(:content, :subject, :user_id) 
在控制器

编辑:通过命名空间,我的意思是轨道会产生这样的HTML标签:

<input id="note_content" ... name="note[content]"> 

而不是

<input id="content" ... name="content"> 
4

你需要纠正你的note_params功能是这样的:

def note_params 
    params.require(:note).permit(:content, :subject, :user_id) 
end 

编辑:

你只是使用select_tag;这样,这个数据就不会与noteparams中关联。你需要做f.select_tag作为这个快速修复。

但是,如果你坚持要用select_tag,那么你需要添加note在你的代码以下列方式:

<%= select_tag('note[subject]', options_for_select(["english" ,"math"])) %> 
+0

现在,该主题未保存。 –

+0

不应该。你的“表单”有一些问题。 'subject'应该用于'note'键,但是在你的发布代码中不是这种情况。 –

+0

你可以发布'form'代码吗? –