我正在研究 Rails,从 Rails 4 开始,但使用的是 Rails 3 书。
书: Beginning Rails 3 - Cloves Carneiro Jr. 和 Rida Al Barazi
在某些章节中使用 :format => :js 响应请求
app/views/articles/show.html.erb
<%= render @article %>
<hr>
<h3>Comments</h3>
<div id="comments">
<%= render @article.comments %>
</div>
<% # render :file => 'comments/new' %>
<%= link_to 'new comment', new_article_comment_path(@article, :format => :js), :remote => true, :id => 'new_comment_link' %>
<%= link_to 'Edit', edit_article_path(@article) %> |
<%= link_to 'Back', articles_path %>
但是这段代码:
<%= link_to 'new comment', new_article_comment_path(@article, :format => :js), :remote => true, :id => 'new_comment_link' %>
不工作。
Rendered comments/new.js.erb (2051.2ms)
Completed 500 Internal Server Error in 2065ms
ActionView::Template::Error (stack level too deep):
actionpack (4.0.0) lib/action_dispatch/http/mime_type.rb:245
Rendered c:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/actionpack-4.0.0/lib/action_dispatch/middleware/templates/rescues/template_error.erb within rescues/layout (17.0ms)
我创建了new.js.erb
一个app/views/comments/new.js.erb
:
$("<%= escape_javascript render(:file => 'comments/new') %>").insertAfter('#comments');
$("#new_comment_link").hide();
但在 Google Chrome 控制台中,请求返回HTTP 500。
耙路线:
https://gist.github.com/6904410
路线
Blog::Application.routes.draw do
root :to => "articles#index"
resources :articles do
resources :comments
end
resources :users
resource :session
match '/login' => "sessions#new", :as => "login", :via => 'get'
match '/logout' => "sessions#destroy", :as => 'logout', :via => 'get'
end
模型/文章.rb
class Article < ActiveRecord::Base
validates :title, :presence => true
validates :body, :presence => true
belongs_to :user
has_and_belongs_to_many :categories
has_many :comments
# Check later
# accepts_nested_attributes_for :categories
scope :published, lambda {where("articles.published_at IS NOT NULL")}
scope :draft, lambda {where("articles.published_at IS NULL")}
scope :recent, lambda { published.where("articles.published_at > ?", 1.week.ago.to_date) }
scope :where_title, lambda { |term| where("articles.title LIKE ?", "%#{term}%}") }
def long_title
"#{title} - #{published_at}"
end
def published?
published_at.present?
end
def owned_by?(owner)
return false unless owner.is_a? User
user == owner
end
end
模型/评论.rb
class Comment < ActiveRecord::Base
belongs_to :article
validates :name, :email, :body, :presence => true
validate :article_should_be_published
after_create :email_article_author
def article_should_be_published
errors.add(:article_id, "is not published yet") if article && !article.published?
end
def email_article_author
logger.info("We will notify #{article.user.email} in Chapter 9")
end
end
部分解决
我更改了渲染文件的路径,for:comments/new.html.erb
和作品。
但是,我不知道是否是最好/正确的解决方案。例如:在渲染动作中,没有任何:format
属性。
环境
- 崇高的文字 2
- Windows 7 专业版 x64
- 导轨 4.0.0
- 红宝石 2.0.0
- jQuery 1.10