Ruby on rails 我如何正确使用所属的和有多个?
我已经调试了一整天了。 我的应用程序中有两个模型:teaClass和tea。在teaclass.rb中,我有Ruby on rails 我如何正确使用所属的和有多个?,ruby-on-rails,sqlite,Ruby On Rails,Sqlite,我已经调试了一整天了。 我的应用程序中有两个模型:teaClass和tea。在teaclass.rb中,我有 has_many :teas 在tea.rb中,我有“属于:teaclass” 我试图使url看起来像这样“.teaclasses/:id/teas/:id”所以在teas\u controller.rb中,我将放在过滤器前面:get\u teaClass def show @tea = @teaclass.teas.find(params[:id]) respond_to do |
has_many :teas
在tea.rb中,我有“属于:teaclass”
我试图使url看起来像这样“.teaclasses/:id/teas/:id”
所以在teas\u controller.rb
中,我将放在过滤器前面:get\u teaClass
def show
@tea = @teaclass.teas.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @tea }
end
end
def new
if @teaclass.teas
@tea = @teaclass.teas.new
@teaclass.teas << @tea
#@tea = Tea.new
else
flash[:notice=>"failed"]
@tea = Tea.new
@teaclass.teas << @tea
end
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @tea }
end
end
def get_teaClass
begin
@teaclass = Teaclass.find(params[:teaclass_id])rescue
redirect_to teaclass_path, :notice => "Teaclass Required!"
end
end
有人能帮我吗?多谢各位 如果查看日志,您将看到params包含哪些内容。根据您的代码和解释,参数中没有键
teaclass\u id
。您很可能正在查找:id。如果您想访问:teaclass_id,您可能需要在路由中设置它
match 'controller/:teaclass_id' => 'controller#show'
我试图使url看起来像这样“.teaclass/:id/teas/:id”;所以在teas_controller.rb中,我在过滤器前面加上:get_teaClass
只有当您试图设置嵌套路由时,这才重要,但id听起来并不像您正在这样做
实际上,您需要做的是将外部id添加到数据库中。所以,检查schema.rb并确保该列存在
这是你需要做的。
tea
中实际有外来项class Tea < ActiveRecord::Base
belongs_to :tea_class
end
意见
这真的很重要。确保在创建tea时将:tea\u class\u id作为参数传递,否则它不知道如何进行关联。它在后台,因为您发送params[:tea]
,但实际上是在那些参数中发送tea\u class\u id
所以。。。在你看来,你需要有某种方式让用户选择一个类别,或者像你现在的tea类那样,这通常是通过一个选择框来完成的,当它是一对多关联时
new.html.erb
<% form_for(@tea) do |t| %>
<%= t.collection_select :tea_class_id TeaClass.all, :id, :name %>
<% end %>
然后你可以链接到teas\u classes/pour/teas/chinese
。您应该知道这个命令rake routes
。它将帮助您了解路径是如何工作的
但如果您只是想让链接继续运行,则应如下所示:
<%= link_to "Teas", tea_classes_teas_path(@tea_class)%>
您需要提供
@teas
执行链接,因为它从中获取id,当您单击它时,它会将其作为参数[:teas\u class\u id]`提供给teas\u控制器。你不需要做任何事。它将自动出现在url中。请确保您所有的代码都是正确的,我编辑了它,非常感谢您的编辑:非常感谢,它很有帮助。我的茶几里没有外键,这是主要问题。我构建了我的模型,并在关联的模型文件中输入了“has_many”和“belish_to”。我假设rails会创造所有的数据库关系。显然,rails并没有做到这一点。还有,有没有一种快速的方法可以自动生成所有外键和其他东西(如scaffold)?脚本/生成scaffold name:string teas\u class\u id:integerrun作为一个scaffold,它将生成一个带有所需id的迁移。
class TeaClass < ActiveRecord::Base
has_many :teas
end
def new
@tea = Tea.new
end
def show
@tea = tea.find(params[:id)
end
def create
@tea = Tea.new(params[:tea])
if @tea.save
redirect_to teas_path
else
render :action => 'new'
end
end
<% form_for(@tea) do |t| %>
<%= t.collection_select :tea_class_id TeaClass.all, :id, :name %>
<% end %>
map.resources :tea_classes_ do |tea_classes|
tea_classes :teas
end
map.resources :teas
<%= link_to "Teas", tea_classes_teas_path(@tea_class)%>