我正在尝试从text_area
表单中的字段中获取文本,以使用当前模型的 ID 保存到不同模型中的数据库。
目前,这有效,但只会保存整数。如果我将文本放入“注释”字段,则将其保存为“0”。我怀疑这工作正常,但我的难题缺少一块。这是因为我只希望“票证”保存 note_id,因为每个“票证”将有多个“备注”。
如何使用 ID 将 Note 保存在 Note Model 中,并将其note_id
与此特定工单相关联?
表单 - /app/views/tickets/_form.html.erb
<%= form_for(@ticket) do |f| %>
<% if @ticket.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@ticket.errors.count, "error") %> prohibited this ticket from being saved:</h2>
<ul>
<% @ticket.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.fields_for :notes do |u|%>
<%= u.label :note %>
<%= u.text_area :note, :size => "101x4", :placeholder => "Leave notes here." %>
<% end %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
票证_controller.rb
class TicketsController < ApplicationController
# GET /tickets
# GET /tickets.json
def index
@tickets = Ticket.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @tickets }
end
end
# GET /tickets/1
# GET /tickets/1.json
def show
@ticket = Ticket.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @ticket }
end
end
# GET /tickets/new
# GET /tickets/new.json
def new
@ticket = Ticket.new
@ticket.notes.build
respond_to do |format|
format.html # new.html.erb
format.json { render json: @ticket }
end
end
# GET /tickets/1/edit
def edit
@ticket = Ticket.find(params[:id])
end
# POST /tickets
# POST /tickets.json
def create
@ticket = Ticket.new(params[:ticket])
respond_to do |format|
if @ticket.save
format.html { redirect_to @ticket, notice: 'Ticket was successfully created.' }
format.json { render json: @ticket, status: :created, location: @ticket }
else
format.html { render action: "new" }
format.json { render json: @ticket.errors, status: :unprocessable_entity }
end
end
end
# PUT /tickets/1
# PUT /tickets/1.json
def update
@ticket = Ticket.find(params[:id])
respond_to do |format|
if @ticket.update_attributes(params[:ticket])
format.html { redirect_to @ticket, notice: 'Ticket was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @ticket.errors, status: :unprocessable_entity }
end
end
end
# DELETE /tickets/1
# DELETE /tickets/1.json
def destroy
@ticket = Ticket.find(params[:id])
@ticket.destroy
respond_to do |format|
format.html { redirect_to tickets_url }
format.json { head :no_content }
end
end
end
笔记.rb
class Note < ActiveRecord::Base
belongs_to :ticket
attr_accessible :note, :ticket_id
end
票务.rb
class Ticket < ActiveRecord::Base
attr_accessible :notes_attributes
accepts_nested_attributes_for :notes
end