天天看點

Ruby on Rails——一個完整的例子(六)

這一節我們來學習一下怎樣更新我們建立的部落格。

既然要做變更的操作,我們首先要在controller中添加update方法,update方法與create方法基本是一樣的,不同的是create建立的是一個新的article,而update要有一個更新的對象,是以在create中用到的是Article.new,而在update中用到的則是Article.find,根據article的id來進行查找。

def

create

@article

= Article.

new

(article_params)

if

@article

.save

redirect_to

@article

else

render

'new'

end

end

def

update

@article

= Article.find(params[

:id

])

if

@article

.update(article_params)

redirect_to

@article

else

render

'edit'

end

end

private

def

article_params

params.require(

:article

).permit(

:title

,

:text

)

end

我們還需要建立一個edit頁面,而edit頁面與new頁面的内容也有幾分相似,不同的是,edit頁面通過id已經擷取了article的既存資訊了。

<

h1

>Edit article</

h1

>

<%=

form_with(model:

@article

, local:

true

)

do

|form|

%>

<%

if

@article

.errors.any?

%>

<

div

id

=

"error_explanation"

>

<

h2

>

<%=

pluralize(

@article

.errors.count,

"error"

)

%>

prohibited

this article from being saved:

</

h2

>

<

ul

>

<%

@article

.errors.full_messages.

each

do

|msg|

%>

<

li

>

<%=

msg

%>

</

li

>

<%

end

%>

</

ul

>

</

div

>

<%

end

%>

<

p

>

<%=

form.label

:title

%>

<

br

>

<%=

form.text_field

:title

%>

</

p

>

<

p

>

<%=

form.label

:text

%>

<

br

>

<%=

form.text_area

:text

%>

</

p

>

<

p

>

<%=

form.submit

%>

</

p

>

<%

end

%>

<%=

link_to

'Back'

, articles_path

%>

 與此相對應,我們還需要在controller中添加一個edit方法,這個方法中不要太多操作,隻需要根據article id将編輯對象找到就可以了。

def

new

@article

= Article.

new

end

def

edit

@article

= Article.find(params[

:id

])

end

def

create

@article

= Article.

new

(article_params)

if

@article

.save

redirect_to

@article

else

render

'new'

end

end

 根據前面的講解内容在相關view中加入一些遷移語句,我們就把article的更新功能實作了。

Ruby on Rails——一個完整的例子(六)
Ruby on Rails——一個完整的例子(六)