Rails 4 belongs_to/has_many 关系无效

Rails 4 belongs_to/has_many relationship not working

我成功地建立了几个 HABTM 关系,没有任何问题,但由于某种原因,我无法建立 belongs_to/has_many 关系记录值。

  1. 一篇文章belongs_to一种类型(新闻、社论、编年史等)
  2. A类has_many篇
  3. Schema.db 显示 type_id 整数列,模型使用 belongs_to 和 has_many 并且文章类型的下拉列表出现在 new/edit 文章页数。
  4. 但是在从下拉列表中选择类型时(例如 'chronicle'),它说它成功创建或编辑了文章,但没有注册文章和 [=42= 之间的 link ].回去编辑同一篇文章时,下拉列表只显示顶部类型 ('analysis'),而不是 'chronicle'。

所以不确定我哪里出错了。以下是所有相关位,从数据库开始。

来自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 %>

有什么想法吗?

您需要将 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

的变化

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

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