在表单中包括 Rails 联接表字段可以通过以下步骤实现:
config/application.rb
文件中设置 form_with
函数,该函数将创建一个包含数据库表单域的表单。create
方法,该方法将调用 create
方法在数据库中创建新的数据记录。connection
方法,该方法将使用 ActiveRecord 连接到数据库。form_with
函数将其包含在表单中。例如,在 app/controllers/posts_controller.rb
中:
class PostsController < ApplicationController
def create
@post = Post.new(post_params)
if @post.save
redirect_to @post, notice: 'Post was successfully created.'
else
render :new
end
end
private
def post_params
params.require(:post).permit(:title, :content, :category_ids => [])
end
end
在 app/models/post.rb
中:
class Post < ApplicationRecord
has_many :comments
belongs_to :category
def connection
ActiveRecord::Base.connection
end
end
在 app/views/posts/new.html.erb
中:
<%= form_with(model: post, local: true) do |form| %>
<% if post.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(post.errors.count, "error") %> prohibited this post from being saved:</h2>
<ul>
<% post.errors.each do |error| %>
<li><%= error.first %>:</li>
<ul>
<li><%= error.last %></li>
</ul>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= form.label :title %>
<%= form.text_field :title, id: :post_title %>
</div>
<div class="field">
<%= form.label :content %>
<%= form.text_area :content, id: :post_content %>
</div>
<div class="field">
<%= form.label :category_ids %>
<%= form.collection_select(:category_ids, Category.all, :id, :name, { id: :post_category_ids }) %>
</div>
<div class="actions">
<%= form.submit %>
</div>
<% end %>
在 config/application.rb
中设置 form_with
函数:
config
领取专属 10元无门槛券
手把手带您无忧上云