Show action in partial won't display in index view - rails

青春壹個敷衍的年華 提交于 2019-12-25 00:16:41

问题


I have my show action within a partial called properties/_property_details.html.erb that I'm trying to display with ajax within the index action's view.

properties/index.html.erb:

<div id="showdiv">
    <%= render :partial => 'property_details' %>
  </div>

properties/_property_details.html.erb:

<div id="response">
<h3>
<%= [@property.Address,@property.City,"FL"].join(", ") %> <%= @property.Zip %></h3> 
etc etc     </div>

However, when I try to load the index page the @property variable of the show action is nil so I get an

undefined method `Address' for nil:NilClass

presumably because there is no (params[:id]) for the show action as required in the properties_controller:

def show
@property = Property.find(params[:id])

respond_to do |format|
  format.js {render :partial => 'property_details' ,:layout => false}
  format.html
end

end

But if that's the case then I should be able to hard code a value for @property in the show action just to test this but the following code still gives the same undefined method for nilclass error when I try to load the index page containing the partial:

def show
  @property = Property.find(1)

respond_to do |format|
  format.js {render :partial => 'property_details' ,:layout => false}
  format.html
end

end

Why is @property coming back as nil? I opened the rails console and did p = Property.find(1) and got a property returned so for some reason the partial isn't listening to the show action in the controller when it's within my index page.

The partial works fine when it's within the properties/show.html.erb like this:

<div class="twothirds">
<%= render :partial => 'property_details' %>
</div>
<div class="onethird">
<%= render :partial => 'property' %>
</div>

So it's only when I'm trying to put the partial within my index page that it doesn't work. What am I doing wrong?


回答1:


This is my first attempt at Ajax so I was mistakenly including the partial for the show action in the index action before the user had clicked on a link to display the show action. So I've replaced the partial in the index action with just an empty div and I replace the empty div with the partial through ajax only when the user clicks on a property link to view a property through the show action.



来源:https://stackoverflow.com/questions/16425641/show-action-in-partial-wont-display-in-index-view-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!