开发者

Pulling in associated data with an :include or :join?

Newbie question here! I'm building a simple application that allows users to create and accept challenges. I want to list on one page all challenges, as well as just the challenges the user has accepted. I'm having a bit of trouble doing the latter because I can't manage to pull in the name of the challenge a user has accepted in my view.

My schema looks like this:

create_table "challenge_lists", :force => true do |t|
t.string   "name"
t.date     "created_on"
t.datetime "created_at"
t.datetime "updated_at"
t.integer  "user_id"
end

create_table "accepted_challenges", :force => true do |t|
t.integer  "user_id"
t.integer  "challenge_list_id"
t.date     "date_accepted"
t.datetime "created_at"
t.datetime "updated_at"
end

Models / Associations:

class ChallengeList < ActiveRecord::Base
has_one :user
has_many :accepted_challenges
end

class AcceptedChallenge < ActiveRecord::Base 
belongs_to :user
belongs_to :challenge_list
has_many :updates
end

Controller:

def index
@challenge_lists = ChallengeList.all
@user_challenges = current_user.accepted_challenges.find(:all, :include => :challenge_list)

respond_to do |format|
  format.html # index.html.erb
  format.xml  { render :xml => @challenge_lists }
end

I would like to be able to call user_challenges开发者_高级运维.name and get back the name of the user's accepted challenges. Any ideas?


You are pretty close, but it seems the problem is that you try to get the name of the collection of challenges. If you only want to extract the names you could do like this:

>> @user_challenges.map(&:name)
=> ["name1", "name2", "name3"]

But if you want to print it in your views, you would probably be better of with using a block:

<h1>Challenges for: <%= current_user.name %></h1>
<% @user_challenges.each do |challenge| %>
<p><%= challenge.name %></p>
<% end %>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜