assign a model's attribute through association
- by justcode
I'm new to rails and working on a rails app and I'm stuck pondering this issue.
I have three models
class product < ActiveRecord::Base
attr_accessible :name, :issn, :category
validates_presence_of :name, :issn, :category
validates_numericality_of :issn, :message => "has to be a number"
has_many :user_products
has_many :users, :through => :user_products
end
class UserProduct < ActiveRecord::Base
attr_accessible :price, :category
validates_presence_of :price, :category
validates_numericality_of :price, :message = "has to be a number"
belongs_to :user
belongs_to :product
end
class user < ActiveRecord::Base
# devise authentication here
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me
has_many :user_products
has_many :products, :through = :user_products
end
here is my new.html.erb
<div class="MainBodyWrapper">
<div class="span8">
<div id="listBoxWrapper">
<fieldset>
<%= form_for(@product, :html => { :class => "form-inline" }, :style => "margin-bottom: 60px" ) do |f| %>
<div class="control-group">
<label class="control-label" for="name">name</label>
<div class="controls">
<%= f.text_field :price, :class => 'input-xlarge input-name', :id => "name" %>
</div>
</div>
<div class="listingButtons">
<button class="btn btn-info"></i>Add</button>
<a class="btn">Upload Pictures (anytime)</a>
</div>
</fieldset>
</div>
</div>
There are reasons why I want to setup the models this way.
So the question is this: I want the user to enter the info for the product in the form but it also involves putting in the price of the product which exists in a different model/table (user_product) that is associated with product. How can I do this? You can see that my form_for uses @product.
Any help will be appreciated.