Reputation: 693
I'm using rails 3.2.3 and am having trouble assigning a value in my HABTM relation.
Basically I have got 2 models, Product and User. When I create a new Product, I want to insert in the Products_Users middle table the inserted values.
It has to be a HABTM as in the future I want to be able to say "user x can also edit that product", instead of just the product's original creator.
My models: (other relations omitted for simplicity)
product.rb
class Product < ActiveRecord::Base
has_and_belongs_to_many :users
accepts_nested_attributes_for :users
attr_accessible <product attributes>, :user_ids, :user_id #it says cant mass assign user_ids so I also added the :user_id, but then it says unknown attribute :user_id
end
user.rb
class User < ActiveRecord::Base
has_and_belongs_to_many :products
attr_accessible :user_id <plus the user attributes>
end
My products controller has the default actions and code from scaffolding.
The problem may also lie in my View. I also have a HABTM relation between products and categories and it as all fine (I choose the categories from a checkbox list)
But how can I insert in the Products_Users table the new line after an already logged user creates a new product?
Im trying to use in my view after in the form:
<%= f.hidden_field :product_id, :value => params[:id]%> #What to put here if the product isn't tecnically created?
<%= f.hidden_field :user_id, :value => current_user.id%>#This "current_user.id" works in other views.
This is not working, and makes little sense also, is it possible to achieve what I am trying to do?
Thanks for your help
Upvotes: 0
Views: 933
Reputation: 693
I deleted the hidden fields
and added this after the save:
user=current_user
@product.users << user
Hope it helps someone.
Regards
Upvotes: 4