0

My current goal in my first rails project is to have a button that will create a @my_tea using the attributes of a @tea (show page). This is the error I am getting:

'undefined method `my_teas_path' for #<#:0xa578cf8>

I have tried having the form in a _new partial inside my_teas/ and inside teas/_add_tea both have given me the same error. Anyway here is my code as it stands. View:

<%= form_for([@user, @my_tea]) do |f| %>
    <%= f.hidden_field :name, :value => @tea.name %>
    <%= f.hidden_field :tea_type, :value => @tea.tea_type %>
    <%= f.hidden_field :store, :value => @tea.store %>
    <%= f.hidden_field :user_id, :value => current_user.id %>

    <%= fields_for [@user, @tea_relationship] do |r| %>
        <%= r.hidden_field :tea_id, :value => @tea.id %>
    <% end %>

<%= f.submit "Add Tea", class: "btn btn-large btn-primary" %>
<% end %>

my_tea controller

def new
  @my_tea = MyTea.new
end

def show
  @my_tea = MyTea.find(params[:id])
end

def create
  @my_tea = MyTea.new(params[:my_tea])
  if @my_tea.save
    flash[:success] = "Tea added to your teas!"
  else
    redirect_to user_path
  end
end

Teas controller:

def show
    @tea = Tea.find(params[:id])    
    @my_tea = MyTea.new
    @tea_relationship = TeaRelationship.new
end

Routes

resources :users do
            resources :my_teas
    end
    resources :teas 

Models:

class User < ActiveRecord::Base
has_many :my_teas, :dependent => :destroy
has_many :tea_relationships, :dependent => :destroy

class MyTea < ActiveRecord::Base
belongs_to :user

class TeaRelationship < ActiveRecord::Base
  belongs_to :user, class_name: "User"
end

Tea model doesn't belong to anything.

Please help rails community your my only hope :p

Update changing my form to this

<%= form_for([@user, @my_tea]) do |f| %>
    <%= f.hidden_field :name, :value => @tea.name %>
    <%= f.hidden_field :tea_type, :value => @tea.tea_type %>
    <%= f.hidden_field :store, :value => @tea.store %>
    <%= f.hidden_field :user_id, :value => current_user.id %>

    <%= fields_for @tea_relationship do |r| %>
        <%= r.hidden_field :tea_id, :value => @tea.id %>
    <% end %>

<%= f.submit "Add Tea", class: "btn btn-large btn-primary" %>
<% end %>

it works and the @my_tea submits but the @tea_relationship doesn't.

4

1 回答 1

0

因此,从事物的外观和一瞥中,您似乎正在尝试做一些嵌套形式。看起来你也有一个多对多的关系(tea.rb <=> tea_relationship.rb <=> my_tea.rb)确保你的模型设置正确。

多对多

我不确定你为什么要这样做[@user, @my_tea]

嵌套表格

应该更符合

<%= form_for @my_tea, :url => posting_path do |f| %>    
    <%= f.simple_fields_for :teas, @my_tea.teas.build do |x| %>
            ...
    <%end%>
    ...
<%end%>

希望有帮助!

于 2012-04-26T00:44:42.377 回答