例如,我的索引视图包含数据库中的所有对象。而不是单击“创建”按钮,我希望在不使用Ajax刷新页面的情况下完成它。怎么做?如何为此目的更改控制器?提前谢谢。
我的控制器
class ArticlesController < ApplicationController
before_filter :authorize, only: [:edit, :new, :destroy]
def index
@articles = current_user.articles
end
def show
@article = Article.find(params[:id])
redirect_to users_path
end
def edit
@article = Article.find(params[:id])
end
def new
@article = Article.new
end
def create
@article = current_user.articles.build(article_params)
if @article.save
redirect_to user_articles_path(current_user)
else
render 'new'
end
end
def update
@article = Article.find(params[:id])
respond_to do |format|
if @article.update(article_params)
format.html {redirect_to user_articles_path(current_user), notice: 'Post was successfully updated'}
format.json { head :no_content }
else
format.html {render action: 'edit' }
end
end
end
def destroy
@article = Article.find(params[:id])
@article.destroy
respond_to {|format| format.js }
end
private
def article_params
params.require(:article).permit(:title)
end
end
答案 0 :(得分:2)
对于 Ajax ,您需要一个带有JS
选项的 表单/链接/按钮 , 控制器操作 ,以处理#new.html.erb
<%= form_for @article, remote: true do |f| %>
<div class="field">
<%= f.label :title %><br>
<%= f.text_field :title %>
</div>
<% end %>
<b>List of Articles</b>
<ul id="articles">
<%= render @articles %>
</ul>
请求和相应的视图页。
new
如您所希望用于创建文章,请更改您的create
和#articles_acontroller
def mew
@article = Article.new
@articles = current_user.articles
end
def create
@article = current_user.articles.build(article_params)
if @article.save
respond_to do |format|
format.html { redirect_to user_articles_path(current_user) }
format.js
else
render 'new'
end
end
end
方法,如下所示
create.js.erb
添加#create.js.erb
$("<%= escape_javascript(render @article) %>").appendTo("#articles");
文件
_article.html.erb
并<li><%= article.title %></li>
显示创建的文章。
{{1}}