2012-11-01 39 views
0

这里是我的问题,我有三个型号:节省用的has_many关联模型

产品型号

class Product < ActiveRecord::Base 
    attr_accessible :description, :title, :photo 
    has_many :votes 

    has_attached_file :photo, :styles => { :medium => "300x300" } 

    before_save { |product| product.title = title.titlecase } 

    validates :title, presence: true, uniqueness: { case_sensitive: false } 
    validates :photo, :attachment_presence => true 

end 

的usermodel

class User < ActiveRecord::Base 
    def self.from_omniauth(auth) 
     where(auth.slice(:provider, :uid)).first_or_initialize.tap do |user| 
     user.provider = auth.provider 
     user.uid = auth.uid 
     user.name = auth.info.name 
     user.oauth_token = auth.credentials.token 
     user.oauth_expires_at = Time.at(auth.credentials.expires_at) 
     user.save! 
     end 
    end 
end 

VoteModel

class Vote < ActiveRecord::Base 
    belongs_to :product 
    attr_accessible :user_id 
end 

现在我需要保存在我的Vo上用ProductId和UserId模拟一条记录。但我不知道如何做到这一点,任何人都可以帮助我吗?

UPDATE


这里是我的投票视图

<%= form_for @vote, :html => { :multipart => true } do |f| %> 

    <%= f.label :user_id %> 
    <%= f.text_field :user_id %> 

    <%= f.label :product_id %> 
    <%= f.text_field :product_id %> 

    <%= f.submit "Crear Producto" %> 
<% end %> 

<%= link_to 'Cancel', root_path %> 

,这里是控制器

class VotesController < ApplicationController 

    def create 
     @some_product = Product.find(params[:id]) 
     some_user = current_user 
     vote = Vote.create(:user => some_user, :production => some_product) 
     save! 
    end 

end 
+0

所以,你只是想创建一个投票属于某个产品和某个用户的记录?只需使用一个标准表单来为产品指定一个hidden_​​field,然后根据current_user生成表决。我真的不明白你的错误或问题。 –

+0

嗨,以及我试图在我的轨道控制台上执行此操作:user = User.first product = Product.first Vote.create(user,product) 然后出现此错误NoMethodError:undefined method'stringify_keys'对于#<用户:0x007ffba2361e38> – Jean

+0

以及它期待的产品和用户的ID。它需要是投票。创建(user_id:some_user's_id,product_id:some_product's_id) –

回答

0

首先 - 你的协会,应在所有车型进行正确定义:

class Product < ActiveRecord::Base 
    has_many :votes 
    #... 
    # bonus - to know who are the users who voted for the product 
    has_many :users, :through => :votes 
end 

class User < ActiveRecord::Base 
    has_many :votes 
    #... 
    # bonus - to know what products a user has voted on 
    has_many :products, :through => :votes 
end 

class Vote < ActiveRecord::Base 
    belongs_to :product 
    belongs_to :user 
    #... 
end 

储蓄应该是直截了当

Vote.create(:user => some_user, :production => some_product) 

从产品访问票

some_product.votes 

从产品访问谁票的用户

some_product.users 
+0

感谢tamersalama,Vote.create(:user => some_user,:production => some_product)会在我的投票控制器上创建操作,对吧?如果你可以帮助我的观点,我真的很感谢 – Jean

+0

我刚刚发布了控制器和投票的看法,因为我得到这个错误:未定义的方法'model_name'为NilClass:类 – Jean

+0

因为它是'form_for @vote ' - params [:id]将代表@vote的id。你应该使用'Product.find(params [:vote] [:production_id])''。我知道你的表单只是一个临时表单(原型),因为我不认为你需要在文本字段中添加用户标识和产品标识。还有一件事:您应该将Vote视为任何其他模型,即:您可以使用Rails脚手架生成器来构建您可以扩展的基本Controller/Model/View。 – tamersalama

相关问题