我有两个类用户/ Blip,我通过User_blips连接表加入。但是当我在表单中提交Blip时,它不会将任何数据保存到连接表中。你能帮我搞清楚为什么吗? (作为一个额外的问题,即使我把#34; sentence_id"放在强大的参数中,它仍然会抛出一个错误,说它未被允许)
Blip模型:
has_many :users, through: :user_blips
has_many :user_blips, dependent: :nullify
用户模型:
has_many :blipped_users, through: :user_blips, source: :blip
has_many :user_blips, dependent: :nullify
Blip create method:
def create
@sentence = Sentence.find params[:sentence_id]
@blip = Blip.new blip_params
@blip.sentence = @sentence
if @blip.save
flash[:success] = "Blip created successfully"
redirect_to root_path
else
flash[:alert] = "Your blip was not created"
redirect_to root_path
end
end
def blip_params
params.require(:blip).permit(:body)
end
Blip Create上的控制台消息:
Started POST "/sentences/1/blips" for 127.0.0.1 at 2015-02-22 12:13:58 -0800
Processing by BlipsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"bsXf7SqWJxv2XjOy79RDvDcpJTZnFJhJj+R50CzBFPyqbHsgo5jt vdrpFuOjHmZ0q+pIyT5tPdR0Ia2cXCJcGQ==", "blip"=>{"'sentence_id'"=>"1", "body"=>"ddsdsds"}, "sentence_id"=>"1"}
Sentence Load (0.3ms) SELECT "sentences".* FROM "sentences" WHERE "sentences"."id" = $1 LIMIT 1 [["id", 1]]
Unpermitted parameter: 'sentence_id'
(0.2ms) BEGIN
SQL (0.4ms) INSERT INTO "blips" ("body", "sentence_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id" [["body", "ddsdsds"], ["sentence_id", 1], ["created_at", "2015-02-22 20:13:58.255772"], ["updated_at", "2015-02-22 20:13:58.255772"]]
(0.4ms) COMMIT
Redirected to http://localhost:3000/
Completed 302 Found in 11ms (ActiveRecord: 1.3ms)
答案 0 :(得分:1)
您可以在加入表has_and_belongs_to_many
rails guide
association
blips_users
用户模型:
has_and_belongs_to_many :blips
Blip模型:
has_and_belongs_to_many :users
迁移:
rails generate migration create_blips_users user_id:integer blip_id:integer; rake db:migrate
控制器:
def create
user = User.first # or maybe current_user
user.blips << Blip.new(create_params)
end
def create_params
params.require(:blip).permit(:body, :sentence_id)
end
这将创建blip
及其与user