繁体   English   中英

Rails的4的belongs_to / has_many关系不起作用

[英]Rails 4 belongs_to/has_many relationship not working

我已经设法建立了一些HABTM关系,没有任何问题,但是由于某些原因,我无法使belongs_to / has_many关系记录这些值。

  1. 文章属于类型(新闻,社论,编年史等)
  2. 类型has_many文章
  3. Schema.db显示type_id整数列,模型使用longate_to和has_many,并且在新/编辑文章页面的表单中出现文章类型的下拉列表。
  4. 但是在从下拉列表中选择一种类型(例如“年代”)时,它表示成功创建或编辑了文章,但未注册文章和“年代”之间的链接。 回到编辑同一篇文章时,下拉列表仅显示顶部类型(“分析”),而不显示“年代”。

所以不确定我要去哪里。 这是所有相关的位,从数据库开始。

从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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM