Erik Mandke
Erik Mandke

Reputation: 1667

Ruby on Rails -- Navigation Properties :o?

I'm new to Rails and I have two models (Ticket, User). One Ticket has one user - One User has_many tickets.

I would like to display "the username of a ticket" on an overview page..

I already set my models and assoziations. The following code should show a 3-column table with the username in the middle, but I get an error :(

"undefined method `users' for ..."

I'm coming from C# using Entity Framework.. I thought RoR does understand the expression "article.user.firstname"

<% @tickets.each do |article| %>
       <tr>
         <td class="cell"><%= article.title %></td> //fine
         <td class="cell"><%= article.user.firstname %></td> // le error :(
         <td class="cell"><%= article.description %></td> //fine
       </tr>
     <% end %>

Could someone show me how to archive this ?

User.rb

class User < ActiveRecord::Base
has_many :tickets, dependent: :destroy
end

Ticket.rb

class Ticket < ActiveRecord::Base
belongs_to :user
end

ticket_controller.rb

class TicketsController < ApplicationController

def index
    @tickets = Ticket.all.includes(:user)
end

def new 
@users = User.all   

end

def create
    @ticket = Ticket.new(article_params)

    @ticket.save
    redirect_to @ticket
end

def show
    @ticket = Ticket.find(params[:id])
end 

private
def article_params
        params.require(:ticket).permit(:title, :description)
end


end

UPDATE:

I had to redefine my model with "rails generate model Ticket title:string message:string user_id". After that I ran "rake db:migrate" (after deleting that table, otherwise I got an error).

Then I set assoziations by writing "belongs_to :user" into ticket.rb and "has_many :tickets" into my user.rb-file.

Upvotes: 1

Views: 175

Answers (2)

Frank004
Frank004

Reputation: 228

Can you post your user table, ticket table and ticket controller. to see if you have a syntax error. You say that tickets only have 1 user and you have article.users and not article.user add user to the

def article_params
        params.require(:ticket).permit(:title, :description,:user_id)
end

Can you post the form to use if your getting the current user id on the form

on the migration of the ticket table do you have a t.integer :user_id

The problem I'm noticing is that when you create the list the user is looking for is at this table tickets and not to Users table.That's why you do not give error when using only article.user

on the Console try User.all and see if you got user and then try the same with Ticket.all

Upvotes: 2

Chuck
Chuck

Reputation: 237060

In the comments, you mention you're getting an error along the lines of "undefined method `firstname' for nil:NilClass". This means that your ticket has no user assigned, so the user is nil. You're getting this error because you're trying to treat nil like a User.

Upvotes: 0

Related Questions