我是Rails的新手,正在嘗試爲移動應用創建一個Api。儘管Api會生成json響應,但我還需要一個Web界面來創建數據。我的路線是這樣的:如何在Rails 3.1.3和Mongoid中爲名稱空間嵌套資源創建form_for?
Appone::Application.routes.draw do
namespace :api1 do
resources :reldates do
resources :movies
end
end
end
的RELEASE_DATE模型:
class Api1::Reldate
include Mongoid::Document
include Mongoid::MultiParameterAttributes
include Mongoid::Timestamps
field :release_date, :type => Date
embeds_many :api1_movies
validates_associated :movie
accepts_nested_attributes_for :movie
end
電影型號:
class Api1::Movie
include Mongoid::Document
include Mongoid::MultiParameterAttributes
include Mongoid::Timestamps
field :title, :type => String
field :release_type, :type => String
field :release_number, :type => Integer
embedded_in :api1_reldate, :inverse_of => :api1_movies
end
和reldate show.html.erb:
<p id="notice"><%= notice %></p>
<p>
<b>Release date:</b>
<%= @api1_reldate.release_date %>
</p>
<% if @api1_reldate.api1_movies.size > 0 %>
<h2>Movies</h2>
<% for api1_movie in @api1_reldate.api1_movies %>
<h3><%= api1_movie.title %></h3>
<p><%= api1_movie.release_type %></p>
<p><%= api1_movie.release_number %></p>
<% end %>
<% end %>
<h2>New Movies</h2>
<% form_for([:api1], :url => { :action => :create ,:id => @reldate.movie}) do |form| %>
<p><%= f.label :title %> <%= f.text_field :title %></p>
<p><%= f.label :release_type %> <%= f.text_field :release_type %></p>
<p><%= f.label :release_number %> <%= f.number_field :release_number %></p>
<p><%= f.submit %></p>
<% end %>
<%= link_to 'Edit', edit_api1_reldate_path(@api1_reldate) %> |
<%= link_to 'Back', api1_reldates_path %>
我無法得到這個工作。我可以得到reldate頁面的工作,但之後我點擊提交,我得到這樣一個錯誤:
undefined method `movie' for nil:NilClass
Extracted source (around line #18):
15: <% end %>
16:
17: <h2>New Movies</h2>
18: <% form_for([:api1], :url => { :action => :create ,:id => @reldate.movie}) do |form| %>
19: <p><%= f.label :title %> <%= f.text_field :title %></p>
20: <p><%= f.label :release_type %> <%= f.text_field :release_type %></p>
21: <p><%= f.label :release_number %> <%= f.number_field :release_number %></p>
電影控制器是這樣的:
class Api1::MoviesController < ApplicationController
def create
@api1_reldate = Api1::Reldate.find(params[:api1_reldate_id])
@api1_movie = @api1_reldate.api1_movies.create!(params[:api1_movie])
redirect_to @api1_reldate, :notice => "Movie successfully created!"
end
end
我怎樣才能得到這個工作?我已經嘗試過所有可能的解決方案,但仍然失敗。 此外,我正在使用瑞安貝茨Railcast
在此先感謝。
謝謝馬特。我嘗試了你所建議的解決方案,但它卻不起作用。該帖子用電影控制器更新。 – ags9