Rails 4 fields_for not saving

时间:2014-06-22 08:34:11

标签: ruby-on-rails

我想通过fields_for在照片模型中保存article_id,但不起作用。

article.rb

class Article < ActiveRecord::Base
    belongs_to :user
    belongs_to :category
    has_many :photos
    accepts_nested_attributes_for :photos

photo.rb:

class Photo < ActiveRecord::Base
    belongs_to :article

category.rb

class Category < ActiveRecord::Base
    has_many :articles

articles_controller.rb

class ArticlesController < ApplicationController

  def new
    @article = Article.new
    @category  = Category.find(params[:category])
    @article.photos.build
  end

  def create
    @article = current_user.articles.build(article_params)
    @article.save

   |
   |
   |

private

def article_params
    params.require(:article).permit(:content, :category_id, photos_attributes: [:id, :article_id])
end

_article_form.html.erb

<%= form_for(@article) do |f| %>
    <%= f.hidden_field :category_id %>
    <%= f.text_area :content %>
    <%= f.fields_for :photos do |p| %>
      <%= p.hidden_field :article_id %>
    <% end %>
  <%= f.submit "Post", class: "btn btn-large btn-primary" %>
<% end %>

.schema文章

CREATE TABLE "articles" (
"id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, 
"content" varchar(255), 
"user_id" integer, 
"category_id" integer,
"created_at" datetime, 
"updated_at" datetime);

.schema categories

CREATE TABLE "categories" (
"id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, 
"code" integer, 
"created_at" datetime, 
"updated_at" datetime);

感谢rmagnum2002。

在articles_controller.rb中,我添加了以下内容;

private

def article_params
    params.require(:article).permit(:content)
end

但我没有article_id。 如何为article_id编写代码?


感谢Rich Peck。

Althogh我编辑了articles_controller.rb,我在ArticlesController#new中有NoMethodError。 未定义的方法`build_photo&#39;对于#

articles_controller.rb

  def new
    @article = Article.new
    @article.build_photo

1 个答案:

答案 0 :(得分:1)

<%= f.fields_for :photo do |p| %>

几个月前我们就遇到了这个问题; fields_forform_for个对象的一部分,因此除非在 表单对象上使用f.,否则不会提交。

导轨指南对此方法非常误导 - 您需要使用f.调用它以使其将数据传递给您的参数。

-

<强>控制器

如果您正在使用f.fields_for,则还需要在控制器中build关联数据:

#app/controllers/articles_controller.rb
Class ArticlesController < ApplicationController
   def new
      @article = Article.new
      @article.build_photo #-> build_value is for singluar association; values.build is for multiple
   end

   def create
      @aticle = Article.new(article_params)
      @article.save
   end

   private 

   def article_params
       params.require(:article).permit(photo_attributes: [:your, :attributes])
   end
end