开发者

How To Get Additional Attributes From Has Many Through

开发者 https://www.devze.com 2023-01-07 17:53 出处:网络
I am using Rails 3 beta 4. I have the following models: class Player < ActiveRecord::Base has_many :players_items, :dependent => :destroy

I am using Rails 3 beta 4.

I have the following models:

class Player < ActiveRecord::Base
has_many :players_items, :dependent => :destroy 
has_many  :items, :throu开发者_StackOverflow中文版gh => :players_items
end

class PlayersItem < ActiveRecord::Base
  belongs_to :player 
  belongs_to :item  
end

class Item < ActiveRecord::Base
  has_many :players_items, :dependent => :destroy
  has_many :players, :through =>  :players_items
end

In the players_controller

def items
    @player = Player.find(params[:id])
    @player_items = @player.items
  end

I have the following attributes

--Items Model--
Item_id:Integer
Name:String
Cost:Integer
Description:Text

--PlayersItem Model--
Item_id:Integer
Player_id:Integer
Total:Integer
Traded:Integer

I am trying to print out all the items associated with a player and for each item print out the "Name", "Cost", "Description", "Total", and "Traded" values.

When I call @player_items in the items.html.erb, I can only access the attributes associated with the Item Model and not any of the attributes associated with PlayersItem model.

I am trying to access the attributes from both the items model and players_items model in the same "call" similar to SQL Join Statement like this

SELECT * FROM players_items INNER JOIN items ON players_items.item_id=items.id  
WHERE players_items.player_id = "@player"

Is this possible?


@player = Player.order("created_at").last
@player.players_items.each do |item|
  puts "#{item.player}: #{item.description} cost:#{item.cost}"
end

Has many through is a little weird. Think of it as a model whose name should (ideally) be descriptive of the relationship between the two other models. So maybe if equipment is being distributed to the players you could call the join model distributions or loans or something. The players_items is the naming convention for join tables which aren't going to be addressed directly. I hope that helps!


Used in the controller

@player = Player.find(params[:id], :include => [:items,:players_items])

And in the view

@player.players_items.each do |player| 
puts "#{player.name}: #{player.player.item.description} cost:#{player.item.cost}"
end
0

精彩评论

暂无评论...
验证码 换一张
取 消