wasshiwa
wasshiwa

Reputation: 296

Constructing a new object in Rails that is part of an active record association

This is just a simple question. I was trying to create a new object in Rails by passing in parameters to the constructor. However, when I execute the code, I get

SQLite3::SQLException: no such column: awards.user_id: SELECT "awards".* FROM "awards"  WHERE "awards"."user_id" = 1

which means the object isn't being constructed properly. Should I be using create instead of new? That isn't working either.

def refresh_awards(user)

new_awards = []

if (user.karma < 40 ) #test award

    a = Award.new(:name => "Nobody Award", :description => "From Jonathan", :category => "Community", :value => 1337, :level => 0, :handle => "nobody_award")
    user.awards.append(a)
    new_awards.append(a)

end

new_awards.each do |a|

    flash[:notice] = "You received the " + a.name + "!"

end

end

Upvotes: 0

Views: 65

Answers (1)

Rob d&#39;Apice
Rob d&#39;Apice

Reputation: 2416

Have you add has_many :awards to the User model? Have you added belongs_to :user to the Award model? Have you added the column user_id to the Award model (using a migration)? You'll need to do these three things to be able to use the user.awards method you're using. Read the Rails Guide on Associations for more detail.

Also, append isn't a Ruby method - the closest method would be <<. You would use it like this:

a = Award.new(:name => "Nobody Award", :description => "From Jonathan", :category => "Community", :value => 1337, :level => 0, :handle => "nobody_award")
user.awards << a

But you could neaten this into one line of code using the create method:

a = user.awards.create(:name => "Nobody Award", :description => "From Jonathan", :category => "Community", :value => 1337, :level => 0, :handle => "nobody_award")

EDIT: To create the user_id column in the Award model, run the following code from terminal (while in your app's directory):

rails generate migration AddUserIdToAward user_id:integer
rake db:migrate

Upvotes: 1

Related Questions