0

在 user_sponsorship 上获得未定义的方法错误

app/controllers/user_sponsorships_controller.rb:7:in `new'

这是 new.html.erb:

<% if @event %>
<%= form_for @user_sponsorship, method: :post do |form|  %>
<div class="mike">
<%= form.hidden_field :event_id, value: @event %>
<%= submit_tag "Yes, sponsor event", class: 'btn btn-success' %>
<%= link_to "Cancel", event_path(@event), class: 'btn btn-default'%>
</div>
<% end %>
<% end %>

这是控制器:

class UserSponsorshipsController < ApplicationController
 before_filter :authenticate_user!, only: [:new]

def new
    if params[:event_id]
        @event = Event.find(params[:event_id])
        @user_sponsorship = current_user.user_sponsorship.new(event: @event)
        else
        flash[:error] = "Event required"
     end
end
end

这是模型:

class UserSponsorship < ActiveRecord::Base
belongs_to :user
belongs_to :event

attr_accessible :user, :event
end

如您所知,我对 Rails 还很陌生。在此先感谢您的帮助

4

1 回答 1

1

您的错误很可能是由于这一行

@user_sponsorship = current_user.user_sponsorship.new(event: @event)

用户(最有可能) has_many user_sponsorships 所以该行应该是

@user_sponsorship = current_user.user_sponsorships.new(event: @event)

使用复数形式,它也应该是关联名称(如果您遵循 rails 约定)。

于 2013-03-19T03:40:52.243 回答