在示例guides.rubyonrails.org/getting_started.html之后,我收到了一个错误未定义的方法`articles'for nil:NilClass ,试图在页面上添加文章。
的routes.rb
Rails.application.routes.draw do
root :to => redirect('/pages/1')
resources :articles
resources :pages do
resources :articles
end
视图/物品/ new.html.erb
<h1>New Article</h1>
<%= form_for([@page, @page.articles.build]) do |f| %>
<p>
<%= f.label :item %><br>
<%= f.text_field :item %>
</p>
<p>
<%= f.label :description %><br>
<%= f.text_area :description %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
articles_controller.rb
class ArticlesController < ApplicationController
def new
@article = Article.new
end
def edit
@article = Article.find(params[:id])
end
def create
@page = Page.find(params[:page_id])
@article = @page.articles.create(article_params)
redirect_to root_path if @article.save
end
private
def article_params
params.require(:article).permit(:item, :description)
end
end
我做错了什么?
答案 0 :(得分:2)
您未在new
行动中定义create
。您需要在new
行动中添加类似于edit
所做的内容(也可能是<script type="text/javascript">
function myfunction() {
var firstfield = document.getElementById('firstfield').value;
...repeated.. for 7 more fields...
/* Base 64 Encode the username and password */
var UserPassword64Encoded = User + ":" + Password;
var UserPassword64Encoded = btoa(UserPassword64Encoded);
/* here is where I assemble the URL */
document.getElementById('results').innerHTML = firstfield + "?some_static_info=" +
... repeated 7 more times...;
document.getElementById('results').style.display = "block";
return false;
}
</script>
行动)。
答案 1 :(得分:0)
before_action :load_page
...
protected
def load_page
@page ||= Page.find(params[:page_id])
end