开发者

Error handeling w/ form_for in associated resource

开发者 https://www.devze.com 2023-02-16 22:27 出处:网络
I can\'t seem to get the flow to work right here. I have a Ruby on Rails (2.3.9) application. For the purposes of this question we have only a couple of resources. Boxes and Messages.

I can't seem to get the flow to work right here. I have a Ruby on Rails (2.3.9) application. For the purposes of this question we have only a couple of resources. Boxes and Messages.

Box has_many :messages
Message belongs_to :box

I have created a view located at /boxes/1/new_message where I have the below form_for code. I can successfully create a message from this view. The problem arrises when my validations kick in.

In this case, message.body can't be blank and is validated by message.rb. Once this validation happens, it kicks the user over to the Message.new action and upon successfully filling in the message.body the app can no longer find the @box.id to place in message.box_id.

I have tried just about everything I can think of by not sure how to allow a users to receive a validation and still successfully create a message for a box. See my code below for reference开发者_如何学编程.

/views/boxes/new_message.html.erb

<% form_for [@box, Message.new] do |f| %>
  <%= f.error_messages %>

  <%= f.label :message_title %>
  <%= f.text_field (:title, :class => "textfield-message grid_12 alpha") %>

  <%= f.label :message_body %>
  <%= f.text_area (:body, :class => "textarea-message grid_12 alpha ") %>

  <%= f.submit "Add a Message", :class => 'input boxy' %>       
<% end %>

messages_controller.rb

  def create
    @message = Message.new(params[:message])

    @box = Box.find(params[:box_id])
    @message = @box.messages.build(params[:message])
    @message.user = current_user

    respond_to do |format|
      if @message.save
        flash[:notice] = 'Message was successfully created.'
        format.html {redirect_to @box }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @flash.errors, :status => :unprocessable_entity }
      end
    end
  end

  def new
    @message = Message.new

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


I believe your

@box = Box.find(params[:box_id])

should be

@box = Box.find(params[:id])
0

精彩评论

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