【问题标题】:Why in my links collection contain empty object?为什么在我的链接集合中包含空对象?
【发布时间】: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


【解决方案1】:

据我所知,不要在控制器的任何地方定义link_params。你需要做这样的事情

link_params = params[:link_params] #assuming there is nested params under the name :link_params

【讨论】:

  • 我应该在哪里写,如何使用这个link_params?
  • 当你回答我时,我已经下班回家了。现在我无法使用我的应用程序。我明天试着修。
猜你喜欢
  • 2013-02-20
  • 1970-01-01
  • 2018-04-03
  • 2016-02-13
  • 1970-01-01
  • 2014-03-20
  • 1970-01-01
  • 1970-01-01
  • 2012-05-21
相关资源
最近更新 更多