Rails Unpermitted parameters: topic_ids

birbird · October 25, 2013 · Last by jimmy85 replied at November 10, 2017 · 4108 hits

我有一个多对多关系 Explaination 和 Topic,创建 Explaination 绑定若干 Topics,其他的都对了,就是这个关联一直绑不上,日志说 Unpermitted parameters: topic_ids,请问这是啥情况,知道请指点,谢啦先!

我的 Controller 是这样写的

def create
  params.permit!
  @place = Place.find(params[:place_id])
  @explaination = @place.explainations.create(params[:explaination].permit(:title, :speaker, :speaker_title, :like, :topic_ids))
  @explaination.save

  redirect_to @place
end

其他相关代码如下

class Explaination < ActiveRecord::Base
  belongs_to :place
  has_many :explaination_segments, :dependent => :destroy
  has_and_belongs_to_many :topics

  def segments
    self.explaination_segments
  end
end
class Topic < ActiveRecord::Base
  belongs_to :place
  has_and_belongs_to_many :explainations
end
create_table "explainations_topics", force: true do |t|
  t.integer  "explaination_id"
  t.integer  "topic_id"
  t.datetime "created_at"
  t.datetime "updated_at"
end

create 之后不需要 save 吧

#1 楼 @themorecolor 多谢指点,不过多 save 一次也不致错 我改成这样,就可以了

def create
  params.permit!
  @place = Place.find(params[:place_id])
  @explaination = @place.explainations.create(params[:explaination].permit(:title, :speaker, :speaker_title, :like))
  @explaination.topic_ids = params[:explaination][:topic_ids]
  @explaination.save

  redirect_to @place
end

我猜测,在 create 那一句,explaination 的 id 还没有确定,无法同时往 explainations_topics 插入记录。必须得先把 explaination 生成了,再往他身上绑 topics。

@explaination = @place.explainations.create(params.require(:explaination).permit(:title, :speaker, :speaker_title, :like, topic_ids: []))

#3 楼 @ichord 十分感谢,这样就好了。这是啥道理啊。

You need to Sign in before reply, if you don't have an account, please Sign up first.