0

这是我的问题,我有三个模型:

产品型号

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

用户模型

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

投票模型

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

现在我需要在我的 VoteModel 上保存一条带有 ProductId 和 UserId 的记录。但是我不知道该怎么做,有人可以帮我吗?

更新


这是我的投票视图

<%= 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
4

1 回答 1

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
于 2012-11-01T16:45:14.627 回答