使用has_many关联保存模型

时间:2012-11-01 16:02:59

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.2

这是我的问题,我有三种模式:

产品型号

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

现在我需要使用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

1 个答案:

答案 0 :(得分: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