Tôi đã cố gắng tạo và chỉnh sửa đối tượng bằng cách sử dụng chế độ xem phương thức trong chỉ mục html trong Rails. Tôi đang sử dụng twitter bootstrap trong dự án. Tôi m cho đến nay thành công trong việc tạo ra các đối tượng bằng cách sử dụng phương thức. Để mọi thứ hoạt động, tôi phải tạo một đối tượng có tên @post = Post.new trong hành động chỉ mục của mình.Tạo và chỉnh sửa đối tượng bằng cách sử dụng phương thức trong đường ray
Vì trước khi phương thức chỉnh sửa được hiển thị, đối tượng chỉnh sửa phải sẵn sàng dưới dạng @post = Post.find (params [: id]), nhưng nó xảy ra trong hành động chỉnh sửa.
Đây có phải là cách mà tôi có thể khởi tạo @post cho chế độ xem chỉnh sửa của tôi trước khi nó được hiển thị không?
Dưới đây là mã của tôi:
index.html.erb
<div class="page-header">
<h1>Posts</h1>
</div>
<% @posts do |post| %>
<tr>
<td><%= post.name %></td>
<td><%= post.description %></td>
<td><%= link_to 'Edit', edit_post_path(post), :class => 'btn btn-mini btn-min-standard-width', :data => {:toggle => "modal", :target => "#editItemModal"} , :remote => true %>
<%= link_to 'Destroy', post, confirm: 'Are you sure?', method: :delete, :class => 'btn btn-mini btn-danger btn-min-standard-width' %></td>
</tr>
<% end %>
<%= link_to 'New Item', new_post_path,
:class => 'btn btn-primary btn-standard-width' , :data => {:toggle => "modal", :target => "#newItemModal"} , :remote => true %>
<div id="newItemModal" class="modal hide fade" >
<button type="button" class="close" data-dismiss="modal">×</button></h1>
<div class="page-header">
<h1>New item </h1>
</div>
<%= render :partial => 'form' %>
</div>
<div id="editItemModal" class="modal hide fade" >
<button type="button" class="close" data-dismiss="modal">×</button></h1>
<div class="page-header">
<h1>Edit item </h1>
</div>
<%= render :partial => 'form' %>
</div>
_form.html.erb
<%if @post%>
<%= form_for(@post, :html => { :class => 'form-horizontal', :remote => true }) do |f| %>
<div class="control-group">
<%= f.label :name, :class => 'control-label' %>
<div class="controls">
<%= f.text_field :name %>
</div>
</div>
<div class="control-group">
<%= f.label :description, :class => 'control-label' %>
<div class="controls">
<%= f.text_area :description %>
</div>
</div>
<div class="form-actions">
<%= f.submit nil, :class => 'btn btn-primary' %>
</div>
<% end %>
<% end %>
PostController
class PostsController < ApplicationController
def index
@post = Post.new
@posts = Post.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @posts }
end
end
def show
@post = Post.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @post }
end
end
def new
@post = Post.new
end
def edit
@post = Post.find(params[:id])
respond_to do |format|
format.html
format.json { render json: @post }
end
end
...... ......
Bạn có thể nhận được nhiều câu trả lời hữu ích hơn bằng cách đăng các bit mã –
Câu hỏi được cập nhật với đoạn mã – random
@random bạn có tìm ra câu trả lời này không? –