Accessing Rails Link Table Fields

Asked

Viewed 737 times

1

MODIFIED QUESTION:

I have an application that has 2 tables: Curso and Cargo and a Third Table curso_cargo that makes the HBTM between them. I would like to know how to access a field of this table curso_cargo, to include data in it by a text_field?

I have an application that has 3 tables : Conhecimentos, Cargo and cursos_cargos.

create_table :cargos do |t|
  t.integer :id
  t.string :nome
  t.text :missao
  t.text :atribuicoes
  t.text :formacao
  t.text :experiencia
  t.references :setor
  t.timestamps
end

create_table :conhecimentos do |t|
      t.string :nome
      t.timestamps
    end

create_table :conhecimentos_responsabilidades, :id => false, :force => true do |t|
      t.references :cargo
      t.references :conhecimento
      t.references :nivel
    end

In this last table, I have a nivel_id field, which will keep an id of a level for each knowledge registered for that position. This field will be in one view of positions, where it will be displayed what the existing knowledge and the level of it.

How to create the form , indicating that that Cargo, has a conhecimento with the nível x?

1 answer

1

You are creating the association table curso_cargo needlessly and almost erroneously.

Rails works unanimously, where the convention is about configuration - and that only makes it necessary to use two tables: curso and cargo. If you need to inject information non-associative to its third table (curso_cargo), independent of Rails or not, you are missing - association tables serve only and only to associate entities (X) to entities (Y).

According to the nomenclature of your association table, curso_cargo, I presume that cargo belongs to the curso, one or more courses may share the same position. Therefore, in /app/assets/models/curso.rb, you teach to curso that he holds a post:

class Curso < ActiveRecord::Base
    has_many :cargo
end

And there in /app/assets/models/cargo.rb, you explain that he [the position] belongs to a course:

class Cargo < ActiveRecord::Base
    belongs_to :curso
end

Once this is done, Rails will take care of making the association for you. In addition to this practicality, you are bringing out a great - and standard - practice.

Highlighting, your table curso you will need a cargo_id as follows:

+----+------+----------+
| id | nome | cargo_id |
+----+------+----------+

To manipulate it with x.text_field, you can do:

[...]

<%= f.text_field :curso, :cargo_id %>

[...]
  • I modified the question because I had expressed myself incorrectly on the subject.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.