看看你的应用程序的业务逻辑,有两个故事你必须实现
1)用户可以创建广告(优惠)(这就是您在广告中添加 user_id 的原因)
2)用户可以对广告出价(这很简单 has_many :通过关联)
class User < ActiveRecord::Base
has_many :bids
has_many :advertisements, :through => :bids
has_many :offers, class_name: "Advertisement", foreign_key: :user_id
end
class Advertisement < ActiveRecord::Base
belongs_to :author, class_name:"User", foreign_key: :user_id
has_many :bids
has_many :users, :through => :bids
end
class Bid < ActiveRecord::Base
belongs_to :user
belongs_to :advertisement
end
所以现在,如果你想获得广告作者,你需要打电话
a = Advertisement.last
a.author
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
=> #<User id: 1, created_at: "2013-05-31 06:13:20", updated_at: "2013-05-31 06:13:20">
a.users
User Load (0.1ms) SELECT "users".* FROM "users" INNER JOIN "bids" ON "users"."id" = "bids"."user_id" WHERE "bids"."advertisement_id" = 2
=> [#<User id: 1, created_at: "2013-05-31 06:13:20", updated_at: "2013-05-31 06:13:20">, #<User id: 1, created_at: "2013-05-31 06:13:20", updated_at: "2013-05-31 06:13:20">]
看,它通过加入投标进行最后选择,而第一个只是从用户表中选择。现在它就像您期望的那样工作。
无论如何,回答你的问题:
是的,您需要像这样定义新路线:
resources :advertisements do
member do
post 'bid'
end
end
您需要在您的 AdvertisementsController 中创建自定义操作来执行此操作:
def bid
@advertisement = Advertisement.find(params[:id])
current_user.bids << Bid.new(advertisement: @advertisement, value: params[:bid])
# you may also add some value column in bids table, thats up to you
redirect_to @advertisement
end
形式是这样的:
<%= form_tag(bid_advertisement_path(@advertisement), :method => "post",) do %>
<%= label_tag(:bid, "Make a bid:") %>
<%= text_field_tag(:bid) %>
<%= submit_tag("Submit") %>
<% end %>