开发者

Passing a variable from controller to view, rails

I have a text entry box in my rails app. When a user inserts text and submits it the controller checks the entries table by id to see if the entry exists or not. If the entry does not exist a new entry is put into the table. If the entry does exist then it is updated to contain the new text input.

Right now if a user submits an entry and then edits it and submits it again without reloading the page a new entry is created when it shouldn't be. I noticed that if a new entry is created its id won't be passed to the controller until the page is reloaded. This means that if someone keeps editing a text entry and saving it without reloading, a new entry will be added to the table for each edit.

I want the entry id to be passed to the client as soon as it is created. So that if a user decided to immediately edit the text entry they will be submitting the id of the entry with the text, thus editing the existing entry and not creating a new one.


This is some of the code:

controller:

def edit_description
@msg = ''
@entry = nil
  if params[:entry][:id]==nil || params[:entry][:id]==''
    @entry = Entry.new(params[:entry])
  else
    @entry = Entry.find(params[:entry][:id])
    @entry.title = params[:entry][:title]
    @entry.data = params[:entry][:data]      
  end

if @entry.save
   @msg ='Save Successful'
else
   @msg ='Trouble Saving'    
end   

end

view:

<%= form_remote_tag(
            :url=>{:controller=>"details", :action=>"edit_description"}%>
        <p><textarea rows="10" cols="50" name="entry[data]"><%= (h(@entry.data) unless @entry==nil)%></textarea></p>
        <p>
            <input type="hidden" name="entry[id]" value="<%=(@entry.id unless @entry==nil)%>"/> 
  开发者_开发百科          <input type="submit" value="Save"/>
        </p>                            
    </form>     


Shouldn't this just be edit/update using REST?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜