Creating a new view on a Controller

0

In a Rails project, I created a Scaffold Responsability and consequently Rails created the whole basic structure of this Scaffold.

I've created a has_and_belongs_to_many relationship between a responsability model and a Knowledge model, and there will be several check_box with the knowledges available for a given reponsability. If I put this code in form , it works, but when creating a view nested_knowledges.html.erb the content with check_box's is not being displayed. Any idea what might be happening?

responsabilities_controller.rb

  def knowledges
    params[:responsability][:knowledge_ids] ||= []

    render :nested_knowledges
     @responsability = Responsability.all
     @knowledge = Knowledge.all
  end

model Reponsabilitiy.rb

class Responsability < ActiveRecord::Base
  belongs_to :setor
  has_and_belongs_to_many :knowledges
  validates_presence_of :nome, :setor_id  
  validates_uniqueness_of :nome
  accepts_nested_attributes_for :knowledges
  attr_accessible :atribuicoes, :experiencia, :formacao, :id, :missao, :nome, :setor_id, :knowledge_ids
  default_scope order('nome ASC') 
end

Knowledge.rb model

class Knowledge < ActiveRecord::Base
  has_and_belongs_to_many :responsabilities
  validates_presence_of :nome
  validates_uniqueness_of :nome
  accepts_nested_attributes_for :responsabilities
  attr_accessible :id, :nome, :responsability_ids
  default_scope order('nome ASC') 
end

View nested_knowledges.html.erb

<h1> <%= link_to l(:lbl_responsability), responsabilities_path %> &#187; <%= link_to l(:lbl_knowledge), knowledges_path %> &#187; </h1>

<%= render :partial => 'tabs' -%>

    <div class="box">
  <% for knowledge in Knowledge.find(:all) %>
      <%= check_box_tag "responsability[knowledge_ids][]", knowledge.id,  @responsability.knowledges.include?(knowledge) %>
      <%= knowledge.nome %><br/>
  <% end %>
</div>
    
asked by anonymous 27.05.2014 / 14:28

1 answer

1

Create a new action for your controller this way:

def acao
end

And then create app/views/seu_controlador/acao.html.erb and paste your code into it.

Then edit your routes.rb by doing the following:

resources :seu_controlador do
  member do
    get 'acao'
  end
end

This should create the /seu_controlador/acao GET route pointing to your page.

Always remember to ask your questions in Official Guide .

Update

Try the changes below.

def knowledges
  params[:responsability][:knowledge_ids] ||= []

  # coloque isso antes do :render
  # note que em mudei o nome das variáveis para o plural, para seguir as convensões do Rails
  @responsabilities = Responsability.all
  @knowledges = Knowledge.all

  render :nested_knowledges
end

HTML:

<% @knowledges.each do |knowledge| %>
  <%= check_box_tag "responsability[knowledge_ids][]", knowledge.id,  @responsabilities.knowledges.include?(knowledge) %>
  <%= knowledge.nome %><br/>
<% end %>
    
27.05.2014 / 15:05