更新了
下面的答案是我的新link_to
<%= link_to "Post a Question", new_classifieds_question_path(@classified) %>
和我的控制器
class QuestionsController < ApplicationController
def index
end
def new
@classified = Classified.find(params[:classified_id])
@question = Question.new
end
def create
@classified = Classified.find(params[:classified_id])
@question = Question.new(params[:question])
@classified.questions << @question
if @question.save
flash[:notice] = "Question has been posted"
else
flash[:notice] = "It did not go through"
end
end
end
新路线
resource :classifieds do
resources :questions
end
分类模型
class Classified < ActiveRecord::Base
has_many :questions
end
和问题模型
class Question < ActiveRecord::Base
attr_accessible :question_body, :classifieds_id
belongs_to :classified
end
和我的新错误
Couldn't find Classified without an ID
我有一个带有两个新/创建方法的问题控制器
def new
@question = Question.new
end
def create
@question = Question.new(params[:question])
@question.classifieds_id = @classified.id
#@question.classifieds_id = params[:id]
if @question.save
flash[:notice] = "Question has been posted"
else
flash[:notice] = "It did not go through"
end
end
问题属于分类广告。架构中的问题表具有classifieds_id列。
这是我的问题模型
class Question < ActiveRecord::Base
attr_accessible :question_body, :classifieds_id
belongs_to :classified
end
在我的routes.rb
中resources :questions
以下是我的link_to的一个变体(在我的show.html.erb中)
这是我在另一个控制器中的show方法
def show
@classified=Classifieds.find(params[:id])
end
<td>
<%= link_to "Post a Question", new_question_path(@classified) %>
</td>
我正在尝试传递由问题控制器处理的分类实例的id。
我尝试了很多版本的link_to,就像这样
<td>
<%= link_to "Post a Question", new_question_path(:id => @classified.id) %>
</td>
并且喜欢这个
<td><%= link_to "Post a Question", {:controller => "questions", :action => "new", :classified_id => @classified.id }, :class => "btn btn-default btn-lg" %></td>
<tr>
黑客攻击不起作用,在stackoverflow上搜索问题也不起作用。
我试过在show.html.erb
中这样做 <p>
<%= @classified.id %>
</p>
并输出值。我安装了更好的错误并传入nil value
。
使用gem 'rails', '3.2.13'
答案 0 :(得分:1)
如果你的路线中有嵌套资源......
resources :classifieds do
resources :questions
end
那会给你方法
<%= link_to "Post a question", new_classifieds_question_path(@classified) %>
您的新方法将收到classified_id
def new
@classified = Classified.find(params[:classified_id])
@question = Question.new
end
def create
@classified = Classified.find(params[:classified_id])
@question = Question.new(params[:question]
@classified.questions << @question
...
end
EDIT
抱歉,忘记了路径调用中的_path
,现已修复。