开发者

ruby on rails passing foreign key in a form

Im trying to setup a simple environment:

class Member < ActiveRecord::Base
  has_many :microposts, :dependent => :destroy
end

class Webpage < ActiveRecord::Base
  has_many :microposts, :dependent => :destroy
end

class Micropost < ActiveRecord::Base
  attr_accessor :content

  belongs_to :member
  belongs_to :webpage
end

I am trying to setup an environment that when the 'show' method of a Webpage contains a 'create' form for a Micropost.

Initially, Microposts were only associated with Members - and this was working fine (the member_id is being set upon login a开发者_开发百科s a cookie and that cookie is being stacked to the Micropost.build method).

The problem here is that I cannot pass the webpage_id - I have tried setting the webpage_id as a cookie and passing it, but that was no good. And currently I am trying to pass the webpage_id as a hidden variable.

The controller for Micropost :create

class MicropostsController < ApplicationController
  def create
    @micropost  = current_member.microposts.build(params[:micropost])
    @webpage = Webpage.find(params['webpage_id'])
    @micropost.webpage = @webpage
    if @micropost.save
      flash[:success] = "Micropost created!"
      redirect_to root_path
    else
      @feed_items = []
      render 'pages/home'
    end
  end
end

and the Webpage :show View:

<table class="front" summary="For signed-in members">
    <tr>
      <td class="main">
        <h1 class="micropost">What's up?</h1>
        <%= form_for @micropost do |f| %>
          <%= render 'shared/error_messages', :object => f.object %>
          <div class="field">
            <%= f.text_area :content %>
            <input type="hidden" id="webpage_id" name="micropost[webpage_id]" value="<%= @webpage.id %>"/>
          </div>
          <div class="actions">
            <%= f.submit "Submit" %>
          </div>
        <% end %>
      </td>
    </tr>
</table>

Everytime I submit the create form, I can see the webpage_id being passed but it is not being saved and the error I get is:

"Couldn't find Webpage without an ID"

Any help would be greatly appreciated :)

Cheers,

Damo


You could make the microposts a nested resource of webpage in your routes.rb file.

This way you can make a form:

form_for([@webpage, Micropost.new]) do |f|

It will then POST to:

webpage_microposts POST   /webpage/:webpage_id/microcomments

And you will access the webpage id in your Micropost controller as such:

@webpage = Webpage.find(params[:webpage_id])
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜