【发布时间】:2017-03-10 05:19:51
【问题描述】:
为什么我没有明智地创建带有 nil 参数的集合对象?
routes.rb:
devise_for :users
root to: "posts#index"
resources :posts do
resources :comments, only: [:new, :create]
resources :images do
resources :comments, only: [:new, :create]
end
resources :links do
resources :comments, only: [:new, :create]
end
end
post_controller:
class PostsController < ApplicationController
before_filter :authenticate_user!, :only => [:new, :create]
def index
@posts = Post.all
end
def show
@post = Post.find(params[:id])
end
def new
@post = Post.new
end
def create
@post = Post.new(post_params)
respond_to do |format|
if @post.save
format.html { redirect_to @post, notice: 'Post was successfully created.' }
format.json { render :show, status: :created, location: @post }
else
format.html { render :new }
format.json { render json: @post.errors, status: :unprocessable_entity }
end
end
end
links_controller:
class LinksController < ApplicationController
before_action :set_link, only: [:show, :edit, :update, :destroy]
def index
@links = Link.all
end
def show
end
def new
@post = Post.find(params[:post_id])
@link = @post.links.new
end
def edit
end
def create
@post = Post.find(params[:post_id])
@link = @post.links.new(link_params)
respond_to do |format|
if @link.save
format.html { redirect_to post_path(@post,@link), notice: 'Link was successfully created.' }
format.json { render :show, status: :created, location: @link }
else
format.html { render :new }
format.json { render json: @link.errors, status: :unprocessable_entity }
end
end
end
我在 /posts/:id 中得到 @post.links,我在 views/posts/show.html.erb 上写过:
<%= @post.links %>
我得到了带有空参数的集合:
#<ActiveRecord::Associations::CollectionProxy
[#<Link id: nil, url: nil, created_at: nil, updated_at: nil, post_id: 6>]
为什么?
【问题讨论】:
-
我想除了你上面的东西之外,我还想看看一些东西。传递给控制器动作的参数是什么?你可以从你的日志中得到这些。另外,您使用的是什么版本的 Rails?如果它是 4 或更高,我看不到您将参数列入白名单/黑名单的位置。
-
我用4个版本
标签: ruby-on-rails collections views controllers