Доступ к указанному полю с помощью mongoid / mongodb / rails - PullRequest
2 голосов
/ 29 января 2011

Если у меня есть модель ...

class Post
  include Mongoid::Document
  field :link
  field :title
  field :synopsis
  field :added_on, :type => Date

  validates_presence_of :link

  embeds_many :replies
  references_one :topic
end

и

class Topic
  include Mongoid::Document
  field :category

  referenced_in :post
end

Что бы мне нужно было написать в index.html.erb для доступа к данным в теме или для добавления темы в сообщение.

Я пробовал post.topic, но получаю неопределенную ошибку метода.

Большое спасибо.

Edit:

Вот код index.html

<div id="post">

    <% @posts.each do |post| %>
        <div class="title_container">
            <%= link_to post.title, post.link %> || <%= link_to 'Edit', edit_post_path(post) %> || <%= post.topic %>
        </div>
    <% end %>

    <br />


    <h2>Topics<h2>
    <% for topic in @post.topics %>
        <h3><%= topic.category %></h3>
    <% end %>


</div>

вот этот пост_контроллер

class PostsController < ApplicationController
  # GET /posts
  # GET /posts.xml
  def index
    @posts = Post.all

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

  # GET /posts/1
  # GET /posts/1.xml
  def show
    @post = Post.find(params[:id])

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

  # GET /posts/new
  # GET /posts/new.xml
  def new
    @post = Post.new

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

  # GET /posts/1/edit
  def edit
    @post = Post.find(params[:id])
  end

  # POST /posts
  # POST /posts.xml
  def create
    @post = Post.new(params[:post])

    respond_to do |format|
      if @post.save
        format.html { redirect_to(@post, :notice => 'Post was successfully created.') }
        format.xml  { render :xml => @post, :status => :created, :location => @post }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @post.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /posts/1
  # PUT /posts/1.xml
  def update
    @post = Post.find(params[:id])

    respond_to do |format|
      if @post.update_attributes(params[:post])
        format.html { redirect_to(@post, :notice => 'Post was successfully updated.') }
        format.xml { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml { render :xml => @post.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /posts/1
  # DELETE /posts/1.xml
  def destroy
    @post = Post.find(params[:id])
    @post.destroy

    respond_to do |format|
      format.html { redirect_to(posts_url) }
      format.xml  { head :ok }
    end
  end
end

Edit:

Я также добавляю соответствующий код _form.html.erb.

<div class="field">
    <%= f.label :topic_id %>
    <%= f.collection_select :topic, Post.topic, :id, :category, :prompt => "Select a Topic" %>
</div>

Edit:

Обновление до 2.0.0.rc.7 до сих пор не получается.

Попробовал метод key в видео Railscast (http://railscasts.com/episodes/238-mongoid) просто для удовольствия. Я получаю ошибку "BSON :: InvalidObjectId in PostsController # update".

Ответы [ 3 ]

1 голос
/ 01 февраля 2011

Я предполагаю, что в теме много сообщений? Если вы хотите ссылочную ассоциацию, вы должны изменить ее на эту.

class Post
  #...
  referenced_in :topic
end

class Topic
  #...
  references_many :posts
end

Затем попробуйте изменить строку collection_select следующим образом:

<%= f.collection_select :topic_id, Topic.all, :id, :category, :prompt => "Select a Topic" %>
0 голосов
/ 31 января 2011

@ user593120 Вы пробовали это в вашем index.html.erb

<div id="post">

    <% @posts.each do |post| %>
        <div class="title_container">
            <%= link_to post.title, post.link %> || <%= link_to 'Edit', edit_post_path(post) %> || <%= post.topic %>
        </div>
    <% end %>

    <br />


    <h2>Topics<h2>
    <% @posts.each do |post| %>
        <h3><%= post.topic.category  if post.topic %></h3>
    <% end %>


</div>
0 голосов
/ 29 января 2011

Ваш post.rb файл имеет references_one :topic, но в вашем индексном представлении вы делаете for topic in @post.topics, подразумевая, что пост может иметь много тем. Либо вам нужно изменить модель на «references_many :topics», либо изменить свое представление так, чтобы оно содержало только одну тему на сообщение.

...