简体   繁体   English

将变量从控制器传递到视图,导轨

[英]Passing a variable from controller to view, rails

I have a text entry box in my rails app. 我的Rails应用程序中有一个文本输入框。 When a user inserts text and submits it the controller checks the entries table by id to see if the entry exists or not. 当用户插入文本并提交文本时,控制器将按ID检查条目表,以查看条目是否存在。 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. 我注意到,如果创建了新条目,则在重新加载页面之前,其ID不会传递给控制器​​。 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. 我希望条目ID在创建后立即传递给客户端。 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. 因此,如果用户决定立即编辑文本条目,则他们将提交带有文本的条目ID,从而编辑现有条目,而不创建新条目。


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>     

这不应该只是使用REST进行编辑/更新吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM