Here are my associations:
- As user has many projects
- A project belongs to one user
User model (user.rb)
class User < ActiveRecord::Base
has_many :projects
attr_accessible: :available, :department, :name, :skills, :title, :photo
end
Project modal (project.rb)
class Project < ActiveRecord::Base
belongs_to :user, :foreign_key => :user_id
attr_accessible :project_name
end
Here’s the code in my show.erb.html file
<%= @user.projects.each do |project| %>
<p><%= projects.project_name %></p>
<% end %>
But this just displays two brackets like this “[]”. Which makes me think it’s an empty array.
So when I run Project.find(1) in rails console to see if the project is being associated with the user, it spits out this:
=> #<Project id: 2, project_name: "This is a project. ", created_at: "2012-11-12 02:29:28", updated_at: "2012-11-12 02:29:28", user_id: nil>
User id nil? What gives?!
Anyone know what I’m doing wrong? Thank you!
EDIT:
Here is the migration adding the foreign key:
class AddForeignKeyToProjects < ActiveRecord::Migration
def change
add_column :projects, :user_id, :integer
end
end
EDIT 2
Here is the instances in the controllers (this is probably the problem)
Project controller
def new
@project = Project.new(params[:project], params[:user_id])
end
User controller
def show
@user = User.find(params[:id], params[:project_name])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @user }
end
end
If you used convention name, it means you had a
user_idin Project table, you don’t need to specifyforeign_keyin Project model, you just need:I don’t sure if this is your typo:
About your controller, I suppose you have
current_usermethod, which define current user logged in. So if you want to create new project withuser_idassociated with current_user’s id, you should write this code:If you want to create new project, your
createaction will like this:Those are basic actions I can show you, because I don’t know how you build form, and how your route look like.
When you show a user, if you used RESTful routes, your route will look like this:
What is RESTful routes? If you want to know you should check this Recource routing.
Then, if you want to find a user, you could use
params[:id]:You can not find a user with
params[:project_name], your user model don’t have that attribute, it’s attribute of project.