Reputation: 6841
I'm trying to make a double relation on the same table but i cannot access the data from other tables.
I have a devise table for users, and other one that will have "their posts".
Reclamacoes table
("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
"usuario_reclamante_id" integer,
"usuario_reclamado_id" integer,
"titulo" varchar,
"conteudo" text,
"created_at" datetime NOT NULL,
"updated_at" datetime NOT NULL)
And than, the model reclamacao
class Reclamacao < ActiveRecord::Base
belongs_to :user, foreign_key: "usuario_reclamante_id"
belongs_to :user, foreign_key: "usuario_reclamado_id"
end
The User model
has_many :reclamacao
In the view, when i'm trying to access the user email, doing something like this:
<% @allReclamacoes.each do |reclamacao| %>
<tr>
<td><%= reclamacao.titulo %></td>
<td><%= reclamacao.conteudo %></td>
<td><%= reclamacao.usuario_reclamante_id.email %></td>
<td><%= reclamacao.usuario_reclamado_id %></td>
</tr>
<% end %>
The creating of the element:
def create
@reclamacao = Reclamacao.new reclamacao_params
@reclamacao.usuario_reclamante_id = current_user
if @reclamacao.save
flash[:success] = "criado com sucesso"
else
flash[:error] = "falha ao criar"
end
redirect_to paginainicial_path
end
and than
undefined method `email' for nil:NilClass
Whats the problem in the relation that i'm making?
Upvotes: 0
Views: 502
Reputation: 1434
First off, you're naming both of the belongs_to
associations the same, which will certainly cause problems. You need to explicitly name one or both of them, like this:
class Reclamacao < ActiveRecord::Base
belongs_to :reclamente, class_name: "User", foreign_key: "usuario_reclamante_id"
belongs_to :reclamado, class_name: "User", foreign_key: "usuario_reclamado_id"
end
You can simplify even further by matching the named associations with the foreign key names. Then you can skip the foreign key parts:
class Reclamacao < ActiveRecord::Base
belongs_to :usuario_reclamente, class_name: "User"
belongs_to :usuario_reclamado, class_name: "User"
end
Similarly, you would need to set up 2 separate has_many
associations on the User side.
Also, this line is wrong:
@reclamacao.usuario_reclamante_id = current_user
You need to either set the id to the current_user's id:
@reclamacao.usuario_reclamante_id = current_user.id
..or, even better, use the named association:
@reclamacao.usuario_reclamante = current_user
Finally, to access the email in the view, you need to use the named association:
<td><%= reclamacao.usuario_reclamante.email %></td>
Upvotes: 2