我尝试在数据库中保存记录,在枢轴表中,但是我有一个错误(屏幕)如果我写@video.category_ids = 1它工作,但类别id =1在数据库中
下面我把我的代码,如果你需要更多的信息,请写。
videos_controller.rb
class VideosController < ApplicationController
layout 'master'
before_action :chceck_login
def index
@videos = Video.sortASC
end
def new
@categories = Category.all
end
def create
@video = Video.new(video_params)
@video.category_ids = [video_params]
if @video.save
flash[:notice] = 'The movie has been added successfuly'
redirect_to(:action => 'index')
else
@categories = Category.all
render('new')
end
end
def show
end
def edit
end
def delete
end
private
def video_params
params.require(:video).permit(:title, :url, :description, category_attributes: [:id]).merge(user_id: session[:user_id])
end
end_form_html.erb
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="basic-addon1"><i class="fas fa-tag"></i></span>
</div>
<%= f.text_field :title, placeholder: 'Title', :class => 'form-control', :id => 'title' %>
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="basic-addon1"><i class="fas fa-link"></i></span>
</div>
<%= f.text_field :url, placeholder: 'URL', :class => 'form-control', :id => 'url' %>
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="basic-addon1"><i class="fas fa-edit"></i></span>
</div>
<%= f.text_area :description, placeholder: 'Description', rows: 5, :class => 'form-control', :id => 'description' %>
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="basic-addon1"><i class="fas fa-sitemap"></i></span>
</div>
<%= f.select(:category_id, @categories.map{|t| [t.name, t.id]}, {}, :multiple => true, :class => 'custom-select') %>
</div>video.rb
class Video < ApplicationRecord
belongs_to :user
has_and_belongs_to_many :categories
scope :sortASC, lambda{order("videos.created_at ASC")}
endnew.html.erb
<% @page_title = 'Add Film' %>
<div class='container'>
<div class='row'>
<div class='col s-6'>
<div class="jumbotron jumbotron-fluid bg-info">
<div class="container">
<h1 class="display-4 text-center">ADD NEW FILM <i class="fas fa-plus"></i></h1>
<p class="lead">This is a modified jumbotron that occupies the entire horizontal space of its parent.</p>
</div>
</div>
</div>
<div class='col s-6'>
<%= form_for(:video, :url => {:action => 'create'}) do |f| %>
<%= render(:partial => 'form', :locals => {:f => f}) %>
<%= submit_tag('Add Film', :class => 'btn btn-primary float-right') %>
<% end %>
</div>
</div>
</div>如果你想要的话,我已经把我的项目放在吉特布身上了。
发布于 2018-05-30 13:28:58
我建议作以下修改:
关于2.我不能百分之百地确定确切的解决方案,也许您还应该拒绝参数中的空id (根据提供的屏幕截图,使用.reject!(&:blank?) )--为了分析进一步的问题,在将video_params函数传递给构造函数之前检查它的输出--它基本上应该看起来像预期对象的哈希表示。
编辑更新了2.关于category_ids的修改建议
https://stackoverflow.com/questions/50605337
复制相似问题