很抱歉这个问题,但我找不到我的错误! 在我的项目中,我的模型称为“团队”。 用户可以创建“团队”或“竞赛”。两者之间的区别在于,竞赛需要的数据多于普通团队。 所以我在团队表中创建了列。 嗯...我还创建了一个名为create_contest.html.erb的新视图:
<h1>New team content</h1>
<% form_for @team, :url => { :action => 'create_content' } do |f| %>
<%= f.error_messages %>
<p>
<%= f.label :name %><br />
<%= f.text_field :name %>
</p>
<p>
<%= f.label :description %><br />
<%= f.text_area :description %>
</p>
<p>
<%= f.label :url %><br />
<%= f.text_fiels :url %>
</p>
<p>
<%= f.label :contact_name %><br />
<%= f.text_fiels :contact_name %>
</p>
<p>
<%= f.submit 'Create' %>
</p>
<% end %>
在我的teams_controller中,我创建了以下函数:
def new_contest
end
def create_contest
if @can_create
@team = Team.new(params[:team])
@team.user_id = current_user.id
respond_to do |format|
if @team.save
format.html { redirect_to(@team, :notice => 'Contest was successfully created.') }
format.xml { render :xml => @team, :status => :created, :location => @team }
else
format.html { render :action => "new" }
format.xml { render :xml => @team.errors, :status => :unprocessable_entity }
end
end
else
redirect_back_or_default('/')
end
end
现在,我想在我的团队/ new.html.erb上找到“new_contest.html.erb”的链接。 所以我做了:
<%= link_to 'click here for new contest!', new_contest_team_path %>
当我转到/teams/new.html.erb页面时,出现以下错误:
undefined local variable or method `new_contest_team_path' for #<ActionView::Base:0x16fc4f7>
所以我改变了我的routes.rb,map.resources :teams
改为map.resources :teams, :member=>{:new_contest => :get}
现在我收到以下错误:new_contest_team_url failed to generate from {:controller=>"teams", :action=>"new_contest"} - you may have ambiguous routes, or you may need to supply additional parameters for this route. content_url has the following required parameters: ["teams", :id, "new_contest"] - are they all satisfied?
我认为添加:member => {...}
是正确的做法。所以,你能告诉我该怎么做?我希望有一个像/ teams / new-contest之类的网址。
我的下一个问题:该怎么做(在解决第一个问题之后),验证new_contest.html.erb的所有字段的存在?在我的普通new.html.erb中,用户不需要所有数据。但是在new_contest.html.erb中他做到了。有没有办法只针对一个动作制作validates_presence_of
(在本例中为new_contest)?
更新 现在,我从routes.rb中删除了我的:成员部分并写道:
map.new_contest '/teams/contest/new', :controller => 'teams', :action => 'new_contest'
现在,点击我的链接,它会将我重定向到/ teams / contest / new - 就像我想要的那样 - 但我收到另一个错误:
Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id
我认为此错误是导致@team
<% form_for @team, :url => { :action => 'create_content_team' } do |f| %>
如何解决此错误?
答案 0 :(得分:0)
我不确定你的模型是如何工作的,但在我的代码中我总是写的;
@team.user_id = @current_user.id
而不是
@team.user_id = current_user.id
这意味着id没有被传递给控制器给你错误,不是吗?
答案 1 :(得分:0)
好的,我发现了我的错误。
作为记录:
首先,我忘记在def new_contest
内编写代码。这是:
def new_contest
if @can_create
@team = Team.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @team }
end
else
redirect_back_or_default('/')
end
end
在我的.erb文件中也有几个拼写错误,例如text_fiels而不是text_field或create_content而不是create_contest。
current_user对我来说很好。