Rails 4 belongs_to / has_many关系不起作用

时间:2015-08-06 10:06:54

标签: ruby-on-rails ruby-on-rails-4 has-many belongs-to

我设法设置了一些没有任何问题的HABTM关系,但出于某种原因,我无法使belongs_to / has_many关系记录这些值。

  1. 文章属于一种类型(新闻,社论,编年史等)
  2. A type has_many文章
  3. Schema.db显示了type_id整数列,模型使用belongs_to和has_many,文章类型的下拉列表显示在新/编辑文章页面的表单中。
  4. 但是从下拉菜单中选择一种类型(例如'编年史'),它表示它成功创建或编辑了文章,但未注册文章和编年史之间的链接#39 ;。在返回编辑同一篇文章时,下拉列表只显示顶部类型('分析'),而不是' chronicle'。
  5. 所以不确定我哪里出错了。以下是从数据库开始的所有相关位。

    来自schema.db:

    create_table "articles", force: :cascade do |t|
      t.string   "headline"
      t.string   "lede"
      t.text     "body"
      t.datetime "created_at", null: false
      t.datetime "updated_at", null: false
      t.integer  "type_id"
    end
    
    create_table "types", force: :cascade do |t|
      t.string   "name"
      t.datetime "created_at", null: false
      t.datetime "updated_at", null: false
    end
    

    然后是模特:

    class Article < ActiveRecord::Base
      has_and_belongs_to_many :categories
      has_and_belongs_to_many :regions
      has_and_belongs_to_many :stories
      belongs_to :type
    end
    
    class Type < ActiveRecord::Base
      has_many :articles
    end
    

    文章控制器:

    # GET /articles/new
      def new
        @article = Article.new
        @regions = Region.all.order(:region)
        @categories = Category.all.order(:category)
        @stories = Story.all.order(:story)
        @types = Type.all.order(:name)
      end
    
    # GET /articles/1/edit
      def edit
        @regions = Region.all.order(:region)
        @categories = Category.all.order(:category)
        @stories = Story.all.order(:story)
        @types = Type.all.order(:name)
      end
    
    # POST /articles
    # POST /articles.json
     def create
        @article = Article.new(article_params)
    
     respond_to do |format|
      if @article.save
        format.html { redirect_to @article, notice: 'Article was successfully created.' }
        format.json { render :show, status: :created, location: @article }
      else
        format.html { render :new }
        format.json { render json: @article.errors, status: :unprocessable_entity }
      end
      end
     end
    
    /* …and then at the bottom… */
    
    def article_params
      params.require(:article).permit(:headline, :lede, :body, :category_ids => [], :region_ids => [], :story_ids => [], :type_id => [])
    end
    

    最后在文章形式中:

    <strong>Type:</strong> <%= f.collection_select :type_id, @types, :id, :name %>

    有什么想法吗?

2 个答案:

答案 0 :(得分:0)

您需要将article_params更改为

def article_params
  params.require(:article).permit(:headline, :lede, :body, :type_id, :category_ids => [], :region_ids => [], :story_ids => [])
end

请注意将:type_id => []更改为:type_id

答案 1 :(得分:0)

由于每篇文章记录中只有一个type_id,因此所需的参数不应包含type_id数组。所以将其更改为:type_id而不是:type_id =&gt; []

def article_params
  params.require(:article).permit(:headline, :lede, :body, :type_id, :category_ids => [], :region_ids => [], :story_ids => [])
end