hernan
hernan

Reputation: 37

get attributes from html to controller rails

i have this .html

<% @resources.each do |resource| %>
  <tr>
    <!-- -1 es para mostrar todos los recursos que faltan % -->
    <% if (resource.curso_id = params[:id] or params[:id] ="-1") and resource.cantidad>0 %>
        <td><%= resource.title %></td>
        <td><%= @curso.nombre %></td>
        <td><%= @user.name %></td>
        <!-- %= image_tag(resource.imagen_url, :width => 190, :height => 190) if resource.imagen.present? % -->
        <td><%= resource.cantidad %></td>
        <td><%= link_to 'Show   ', resource %></td>

and this controller:

def index
  if params[:id] != "-1"
    @resources = Resource.where(:curso_id => params[:id])
    @curso = Curso.find(params[:id])
    @user = User.find(@curso.user_id)
  else
    @resources = Resource.all
    # HERE IS THE ERROR. I WANT TO GET THE COURSE BUT I WANT THE FIELD CURSO_ID THAT IS IN RESOURCE TABLE
    @cursos = Cursos.find(@resource.curso_id)
    @user = User.find(@curso.user_id)
  end
end

the part that is above the if works ok. but the part below doesnt work. i want to get an attribute from resource in html and use in my controller. how could it be possible? thank you!

Upvotes: 1

Views: 70

Answers (2)

Mladen Ilić
Mladen Ilić

Reputation: 1765

It seems like your model associations are not set up.

class Resource < ActiveRecord::Base
  belongs_to :curso
end

class Curso < ActiveRecord::Base
  has_many :resources
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :cursos
end

After that, you can simply access them in view template:

<% @resources.each do |resource| %>
  <% resource.curso %>
  <% resource.curso.user %>
<% end %>

Lastly, I'd like to add that using localized names for your model attributes is a real bad practice.

Upvotes: 1

Kumar
Kumar

Reputation: 3126

@resource is not defined. You have defined @resources = Resource.all(notice the s). Plus Resource.all returns an array or objects of type Resource. Please explain what you're trying to achieve.

Upvotes: 0

Related Questions