当前位置: 动力学知识库 > 问答 > 编程问答 >

ruby on rails 3 - Correct way to share a view in the index page

问题描述:

I'm a Ruby-on-Rails newbie, just starting out.

I have an MVC called "account_types", generated via scaffold to produce:

  • controllers/account_types_controller.rb
  • helpers/account_types_helper.rb
  • models/account_type.rb
  • views/account_types/_form, edit, index etc...

Going to localhost:3000/account_types gives me the index view.

What I'd like to do is display the same data as selected from the account_types index method in the application index page as a list.

I wrote a new view called account_types/_list.html_erb as follows:

<ul>

<% @account_types.each do |account| %>

<li><% account.label %></li>

<% end %>

</ul>

I then edited home/index.html.erb (This is based on examples given in other questions on SO):

<%= render :partial => 'account_types/list', :module_types => @module_types %>

However I get

undefined method `each' for nil:NilClass

and the error displays the code from account_types/_list.html.erb where I've written

<% @account_types.each do |account| %>

The scaffolded views work fine, why aren't mine?

Are partials the right thing to use here?

Thanks in advance.

网友答案:

What is the correct way to define an application-wide partial and its variables in rails says to use a before_filter on ApplicationController.

网友答案:

You pass :module_types to partial, but use account_types. As I can see you just need to change your index.html.erb to:

<%= render :partial => 'account_types/list', :account_types => @module_types %>
网友答案:

You can use partials for this if you want, though it would be unnecessary in this case as far as I can tell (they are for sharing chunks of code between several views). In order to get this code to work you'll need to define @account_types in your controller with something like

@account_types = AccountType.all

You can see exact line in your account_types_controller.rb under index action. :module_types => @module_types is not necessary here, since I doubt you defined @module_types either and you don't use module_types in your partial at all.

It's obvious, that you don't understand how Rails works, so I suggest reading through a good tutorial (like this one) before you proceed with whatever you have in mind.

分享给朋友:
您可能感兴趣的文章:
随机阅读: