2016-04-25 55 views
-3

因此,我們目前正在爲重要客戶開發一個網站,並且遇到阻礙進一步發展的障礙。我們正在研究數據庫表之間的關係,其中一個表不識別上述方法。下面是代碼:未定義的方法'名稱'爲零:NilClass

organizers_controller.rb:

# GET /organizers.json 
def index 
    @organizers = Organizer.all 
end 

# GET /organizers/1 
# GET /organizers/1.json 
def show 
end 

# GET /organizers/new 
def new 
    @organizer = Organizer.new 
end 

# GET /organizers/1/edit 
    def edit 
end 

# POST /organizers 
# POST /organizers.json 
def create 
    @organizer = Organizer.new(organizer_params) 

respond_to do |format| 
    if @organizer.save 
    format.html { redirect_to @organizer, notice: 'Organizer was successfully created.' } 
    format.json { render :show, status: :created, location: @organizer } 
    else 
    format.html { render :new } 
    format.json { render json: @organizer.errors, status: :unprocessable_entity } 
    end 
end 
end 

# PATCH/PUT /organizers/1 
# PATCH/PUT /organizers/1.json 
def update 
    respond_to do |format| 
    if @organizer.update(organizer_params) 
     format.html { redirect_to @organizer, notice: 'Organizer was successfully updated.' } 
    format.json { render :show, status: :ok, location: @organizer } 
    else 
    format.html { render :edit } 
    format.json { render json: @organizer.errors, status: :unprocessable_entity } 
    end 
end 
end 

# DELETE /organizers/1 
# DELETE /organizers/1.json 
def destroy 
    @organizer.destroy 
    respond_to do |format| 
    format.html { redirect_to organizers_url, notice: 'Organizer was successfully destroyed.' } 
    format.json { head :no_content } 
end 
end 

private 
    # Use callbacks to share common setup or constraints between actions. 
    def set_organizer 
    @organizer = Organizer.find(params[:id]) 
    end 

# Never trust parameters from the scary internet, only allow the white list through. 
def organizer_params 
    params.require(:organizer).permit(:name) 
end 
end 

show.html.erb:

<p id="notice"><%= notice %></p> 

<p> 
    <strong>Title:</strong> 
    <%= @event.title %> 
    <strong>Organization</strong> 
    <%= @organizer.name %> 
</p> 

<%= link_to 'Edit', edit_event_path(@event) %> | 
<%= link_to 'Back', events_path %> 

相關的錯誤:

undefined method `name' for nil:NilClass 

藉口間距問題,代碼沒有很好地轉換到代碼塊

+0

'@ organizer'爲零,所以你得到這個錯誤。 – dp7

+0

你確定錯誤信息是正確的嗎?我寧願期待「未定義的方法'title'」,因爲你似乎有'@ organizer'實例變量集,但是'@ event'實例變量未設置。 –

+0

從哪裏得到@event。 –

回答

0

如果您註釋掉Organizer.title一行。看看你是否有其他錯誤。它會讓你走上正軌。還要進入控制檯並處理關係。你沒有發佈關係,所以很難知道。像event.organizer.name可能是nesseccary。

0

因此,在與同事交談後,我已經找出了我的問題的答案。奇怪的是,這是一個簡單的答案。我只是需要改變<%= @ organizer.name%>到:

<% @event.organizers.each do |organizer| %> 
    <%= organizer.name %> 
<% end %> 

,這是一個許多一對多的關係,事實上,節目沒有訪問@organizer變量的事實。所以這個循環是顯示正確信息所必需的。無論如何感謝您的回覆,很高興您花了時間!

相關問題