0

ここに私の問題があります.3つのモデルがあります:

製品モデル

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

ここで、ProductId と UserId を含むレコードを VoteModel に保存する必要があります。しかし、私はこれを行う方法がわかりません、誰か助けてもらえますか?

アップデート


ここに私の投票ビューがあります

<%= 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 に答える