嵌套资源:禁止的属性

时间:2014-07-04 13:02:13

标签: ruby-on-rails

我是rails的新手,我得到了ActiveModel::ForbiddenAttributesError。这是我的嵌套资源控制器:

class PostsController < ApplicationController
  respond_to :html, :xml, :json

  def index
    @post=Post.all  
  end

  def new
    @user = User.find(params[:user_id])
    @post = @user.posts.build
    respond_with(@post)
  end

  def create
    debugger
    @user = User.find(params[:user_id])
    @post = @user.posts.build(params[:post])
    if @post.save
      redirect_to user_posts_path
    else
      render 'new'
    end
  end

  def post_params
    params.require(:post).permit(:title, :description, {:user_ids =>[]})
  end
end

1 个答案:

答案 0 :(得分:0)

如果您有以下型号:

<强> post.rb

class Post < ActiveRecord::Base
  belongs_to :user
end

<强> user.rb

class User < ActiveRecord::Base
  has_many :posts
end

您实际上并不需要使用嵌套属性,只需在控制器中执行以下操作:

class PostsController < ApplicationController
  respond_to :html, :xml, :json

  def index
    @post = Post.all  
  end

  def new
    @post = Post.new
    respond_with(@post)
  end

  def create
    @user = User.find(params[:user_id])
    @post = @user.posts.new(post_params) # This will automatically set user_id in the post object

    if @post.save
      redirect_to user_posts_path
    else
      render 'new'
    end
  end

  def post_params
    params.require(:post).permit(:title, :description)
  end
end

虽然我不建议您在网址中使用 user_id 参数。看看devise gem来处理身份验证。