Question

I am trying to create a "favourite" button for my rails site. I have two models, users and materials. I have done the following:

a) I created a new table "favmats" which looks like this in the schema:

create_table "favmats", :force => true do |t|
    t.integer  "user_id"
    t.integer  "material_id"
    t.datetime "created_at",  :null => false
    t.datetime "updated_at",  :null => false
end

b) I set up relationships between the models:

class Favmat
  belongs_to :user
  belongs_to :material
end

class Materials
  has_many :favmats
  has_many :users, :through => :favmats
end

class Users
  has_many :favmats
  has_many :materials, :through => :favmats
end

c) I created a form on the materials show page that should execute code to create the new relationship in the database. There seems to be a problem with this. The code is thus:

<%= form_for @favmat do |f| %>
  <%= f.hidden_field :user_id, value: @user.id %>
  <%= f.hidden_field :material_id, value: @material.id %>
  <%= f.submit "Favourite" %>
<% end %>

d) I created a method in the favmats_controller that looks like this:

def create
  @material = Material.find(params[:id])
  respond_to do |format|
    if @favmat.save
      format.html { redirect_to @material }
      format.js
    else
      format.html { render 'new' }
      format.js
    end
  end   
end

Needless to say, this is not working. Any ideas what I should do? My biggest sources of confusion are where I should create a new favmats object and how.

Was it helpful?

Solution

Your create function is trying to use an :id param that, in a create action, shouldn't exist. It also doesn't build a favmat object, it just tries to save something that doesn't exist.

def create
  @favmat = Favmat.new(params[:favmat])
  respond_to do |format|
    if @favmat.save
      format.html { redirect_to @favmat.material }
      format.js
    else
      format.html { render 'new' }
      format.js
    end
  end   
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top